Nginx服務器安裝部署

1、介紹

Nginx(「engine x」)是一款是由俄羅斯的程序設計師Igor Sysoev所開發高性能的 Web和反向代理服務器,也是一個 IMAP/POP3/SMTP 代理服務器。javascript

2、Nginx部署

1.依賴安裝

yum install zlib zlib-devel openssl openssl-devel pcre pcre-develcss

2.建立用戶

useradd -s /sbin/nologin -r wwwhtml

3.Nginx安裝

wget http://nginx.org/download/nginx-1.18.0.tar.gz
tar fx nginx-1.18.0.tar.gz
cd nginx-1.18.0/
./configure --prefix=/usr/local/nginx-1.18.0 \
--user=www \
--group=www \
--with-http_ssl_module \
--with-cc-opt=-O2 \
--with-cpu-opt=opteron \
--with-http_sub_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--with-http_realip_module \
--with-http_flv_module \
--with-http_mp4_module \
--with-http_random_index_module \
--with-stream \
--with-debug
make && make install
ln -s /usr/local/nginx-1.18.0/ /usr/local/nginx
參數說明:java

--prefix:指定安裝路徑
--with-http_ssl_module:啓用ssl模塊
--with-cc-opt=-O2: 設置 C 編譯器參數
--with-cpu-opt=opteron: 指定編譯的 CPU
--with-http_sub_module:過濾模塊,用於修改網站響應內容的字符串
--with-http_gunzip_module: 爲那些不支持gzip模塊的客戶端解壓縮
--with-http_gzip_static_module:啓用靜態壓縮
--with-http_stub_status_module:啓用狀態模塊
--with-http_realip_module:在訪問日誌中去掉代理IP,記錄真實IP
--with-http_flv_module: 這個模塊支持對FLV(flash)文件的拖動播放
--with-http_mp4_module: 支持H.264/AAC文件爲僞流媒體
--with-http_random_index_module:隨機展現當前目錄下的文件做爲首頁
--with-stream:啓用4層代理
--with-debug:啓用debug日誌
--user:指定nginx運行的用戶

4.啓動服務

/usr/local/nginx/sbin/nginx #啓動
/usr/local/nginx/sbin/nginx -s stop #中止
/usr/local/nginx/sbin/nginx -s reload #重載
/usr/local/nginx/sbin/nginx -t #測試node

5.驗證

http://localhost
Nginx服務器安裝部署linux

3、配置文件詳解

cat /usr/local/nginx/conf/nginx.confnginx

#nginx進程,通常設置爲和cpu核數同樣
worker_processes 4;                        
#錯誤日誌存放目錄 
#錯誤日誌級別:常見的錯誤日誌級別有[debug | info | notice | warn | error | crit | alert | emerg],級別越高記錄的信息越少
error_log  /data1/logs/error.log  crit;  
#運行用戶,默認便是nginx,可不設置
user www       
#進程pid存放位置
pid        /application/nginx/nginx.pid;
#最大文件打開數(鏈接),可設置爲系統優化後的ulimit -HSn的結果
worker_rlimit_nofile 51200;
#cpu親和力配置,讓不一樣的進程使用不一樣的cpu
worker_cpu_affinity 0001 0010 0100 1000;
#工做模式及鏈接數上限
events 
{
  use epoll;       #epoll是多路複用IO(I/O Multiplexing)中的一種方式,可是僅用於linux2.6以上內核,能夠大大提升nginx的性能
  worker_connections 1024;  #;單個後臺worker process進程的最大併發連接數
}
http {
#當fastcgi狀態碼大於300時,將響應轉發給error_page指令處理
  fastcgi_intercept_errors on;
#當被代理的後端狀態碼大於300時,返回給error_page處理
proxy_intercept_errors on;
#默認編碼
  charset  utf-8;
#服務器名字的hash表大小
  server_names_hash_bucket_size 128;
#指定客戶端請求頭buffer大小
  client_header_buffer_size 4k;
#指定客戶端請求中較大的消息頭的緩存最大數量和大小
  large_client_header_buffers 4 32k;
#容許用戶最大上傳數據大小
  client_max_body_size 300m;
#開啓高效文件傳輸模式
  sendfile on;
#激活tcp_nopush參數能夠容許把httpresponse header和文件的開始放在一個文件裏發佈,積極的做用是減小網絡報文段的數量
  tcp_nopush     on;
#設置客戶端鏈接保持活動的超時時間
  keepalive_timeout 300;
 #激活tcp_nodelay,內核會等待將更多的字節組成一個數據包,從而提升I/O性能
  tcp_nodelay on;
#緩衝區代理緩衝用戶端請求的最大字節數
  client_body_buffer_size  512k;
#與upstream server的鏈接超時時間
  proxy_connect_timeout    50;
#nginx跟後端服務器鏈接超時時間(代理讀超時)
  proxy_read_timeout       100;
#發送請求給代理服務器的超時時間
  proxy_send_timeout       50;
#設置代理服務器(nginx)保存用戶頭信息的緩衝區大小
  proxy_buffer_size        16k;
#proxy_buffers緩衝區,網頁平均在32k如下的話,這樣設置
  proxy_buffers            4 64k;
#高負荷下緩衝大小(proxy_buffers*2)
  proxy_busy_buffers_size 128k;
#設定緩存文件夾大小,大於這個值,將從upstream服務器傳
  proxy_temp_file_write_size 128k;
#開啓動態壓縮
  gzip on;
#設置容許壓縮的最小字節數
  gzip_min_length  1k;
#壓縮緩衝區大小
  gzip_buffers     4 16k;
#壓縮版本
  gzip_http_version 1.1;
#壓縮比率。1最小處理最快,9壓縮比最大傳速速度快
  gzip_comp_level 2;
#指定壓縮類型
  gzip_types       text/plain application/x-javascript text/css application/xml;
#和http頭有關,斷送客戶端瀏覽器是否支持壓縮,肯定是否壓縮
  gzip_vary on;
#隱藏版本號
  server_tokens off;
#訪問日誌格式設置
log_format  main  '$remote_addr - $remote_user [$time_local] "$host" "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" $request_time';
access_log  logs/access.log  main;
#反向代理設置
upstream backend_server {
    server   10.0.0.20:81 weight=1 max_fails=2 fail_timeout=30s;
}
狀態值說明:
weight:指定權重
max_fails:最大失敗次數
fail_timeout: max_fails次失敗後,暫停的時間
down:不參與負載
backup:非backup機器down或者忙的時候,請求backup機器
max_conns:指定後端服務器的最大鏈接數
server {
        listen 80;
        server_name www.blpwdev.com;
#若是請求方法不是GET|POST返回444
         if ($request_method !~* GET|POST) {
            return 444;
        }
#禁止某些IP訪問後端服務器
         set $allow true;
         if ($remode_addr ~ 「110.46.120.36」){
            set $allow false;
         }
         if ($allow = false){
            return 404;
         }
        location / {
         proxy_pass http://backend_server;
#當某臺返回錯誤時,繼續分配給下一臺機器處理
         proxy_next_upstream http_500 http_502 http_503 error timeout invalid_header;
#該參數做用是對發送給客戶端的URL進行修改
         proxy_redirect off;
#後端的Web服務器能夠經過X-Forwarded-For獲取用戶真實IP
         proxy_set_header Host $host;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
#防盜鏈
location ~ .*\.(jpg|gif|png)$ {
    valid_referers none blocked www.blpwdev.com;
    if ($invalid_referer) {
        return 403;
    }
    root  /opt/app/code/images;
}
     error_page 404 @proxy_error;
     location @proxy_error {
        rewrite ^ http://www.baidu.com;
    }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
}
}

補充:
nginx的location配置詳解
語法規則: location [=|~|~|^~] /uri/ { … }
=:表示精確匹配,只有徹底匹配上才能生效。
^~:對URL路徑進行前綴匹配,而且在正則以前。
~:表示區分大小寫的正則匹配。
~
:表示不區分大小寫的正則匹配。
/uri:不帶任何修飾符,也表示前綴匹配,可是在正則匹配以後。
/:通用匹配,任何未匹配到其它location的請求都會匹配到。後端

4、Nginx模塊使用

1.rewrite模塊

基本語法: rewrite regex replacement [flag];
上下文:server location if
rewrite配置語法中的flag參數:
last:中止rewrite檢測【若是沒有匹配到,會繼續向下匹配】
break:中止rewrite檢測【若是沒有匹配到,則再也不向下匹配,直接返回結果】
redirect :返回302臨時重定向,地址欄會顯示跳轉後的地址
permanent:返回301永久重定向,地址欄會顯示跳轉後的地址
例子:
rewrite ^/(.*) http://www.baidu.com/$1 permanent;瀏覽器

2.對於鏈接限制limit_conn模塊

limit_conn_zone
語法: limit_conn_zone $variable zone=name:size;
默認值: none
配置段: http
$variable定義鍵,zone=name定義區域名稱,後面的limit_conn指令會用到的。size定義各個鍵共享內存空間大小。如:
limit_conn_zone $binary_remote_addr zone=addr:10m;
limit_conn_log_level
語法:limit_conn_log_level info | notice | warn | error
默認值:error
配置段:http, server, location
當達到最大限制鏈接數後,記錄日誌的等級
limit_conn
語法:limit_conn zone_name number
默認值:none
配置段:http, server, location
指定每一個給定鍵值的最大同時鏈接數,當超過這個數字時被返回503錯誤
如:
limit_conn addr 1;
limit_conn_status
語法: limit_conn_status code;
默認值: limit_conn_status 503;
配置段: http, server, location
limit_rate
語法:limit_rate rate
默認值:0
配置段:http, server, location, if in location
對每一個鏈接的速率限制。參數rate的單位是字節/秒,設置爲0將關閉限速。 按鏈接限速而不是按IP限制,所以若是某個客戶端同時開啓了兩個鏈接,那麼客戶端的總體速率是這條指令設置值的2倍。
例子:緩存

http {
limit_conn_zone $binary_remote_addr zone=limit:10m;
limit_conn_log_level info;
server {
    location ^~ /download/ {
        limit_conn limit 4;
#設置用戶下載文件前10m時不限速
        limit_rate_after 10m;
        limit_rate 200k;
        alias /data/www/download/;
    }
}
}

3. 限制請求數limit_req模塊

limit_req_zone
語法: limit_req_zone $variable zone=name:size rate=rate;
默認值: none
配置段: http
設置一塊共享內存限制域用來保存鍵值的狀態參數
如:
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
說明:區域名稱爲one,大小爲10m,平均處理的請求頻率不能超過每秒一次
limit_req_log_level
語法: limit_req_log_level info | notice | warn | error;
默認值: limit_req_log_level error;
配置段: http, server, location
設置你所但願的日誌級別
limit_req_status
語法: limit_req_status code;
默認值: limit_req_status 503;
配置段: http, server, location
limit_req
語法: limit_req zone=name [burst=number] [nodelay];
默認值: —
配置段: http, server, location
設置對應的共享內存限制域和容許被處理的最大請求數閾值
如:
limit_req zone=one burst=5;
限制平均每秒不超過一個請求,同時容許超過頻率限制的請求數很少於5個。
若是不但願超過的請求被延遲,能夠用nodelay參數,如:
limit_req zone=ttlsa_com burst=5 nodelay;
例子:

http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=6r/m;
    server {
        location  ^~ /download/ {  
            limit_req zone=one burst=5 nodelay;
            alias /data/www/download/;
        }
    }
}

4. ngx_http_realip_module模塊

語法:set_real_ip_from address|cidr|unix;
默認值: —
配置段: http, server, location
例子:
#真實服務器上一級代理的IP地址或者IP段
set_real_ip_from 0.0.0.0/0;
#定義其值替換客戶端地址的請求頭
real_ip_header X-Forwarded-For;
#遞歸地排除直至獲得用戶ip
real_ip_recursive on;

5. ngx_http_sub_module模塊

該ngx_http_sub_module模塊是一個過濾器,經過將一個指定的字符串替換爲另外一個字符串來修改響應
sub_filter
做用:用於替換字符串
用法:sub_filter 要替換的字符串 替換後的字符串,不區分字符串的大小寫
範圍:http server location
默認:-
sub_filter_last_modified
做用:容許在替換期間保留來自原始響應的「Last-Modified」標題字段以促進響應緩存。默認狀況下,在處理期間修改響應的內容時,標題字段被刪除。
用法:sub_filter_last_modified on | off
範圍:http server location
默認:sub_filter_last_modified on
sub_filter_once
做用:指示是否查找每一個字符串以替換一次或重複替換。
用法:sub_filter_once on | off
範圍:http server location
默認:http server location
sub_filter_types
做用:指定MIME類型的字符串替換,除了「 text/html」 以外,還能夠在指定MIME類型的響應中啓用字符串替換。特殊值「 *」匹配任何MIME類型
用法:sub_filter_types mime-type ...
範圍:http server location
默認:sub_filter_types text / html;
例子:

location / {
#把nginx.com替換成baidu.com
           sub_filter 'nginx.com' 'baidu.com';
#把nginx.org替換成baidu.org 
           sub_filter 'nginx.org' 'baidu.org';
           sub_filter_types css/html;   #替換的類型
           sub_filter_once off;     #所有替換
           root  html;
           index  index.html index.htm;
        }

6. stub_status狀態模塊

nginx中的stub_status模塊主要用於查看Nginx的一些狀態信息. 本模塊默認沒有安裝,須要編譯安裝
在nginx配置文件中的server段加上以下配置
location /nginx_status {
stub_status on;
access_log off;
}
返回各項數聽說明:
Active connections: 當前nginx正在處理的活動鏈接數.
server 表示Nginx啓動到如今共處理了 30 個鏈接
accepts 表示Nginx啓動到如今共成功建立 30 次握手
handled requests 表示總共處理了 37 次請求
請求丟失數 = 握手數 - 鏈接數 ,能夠看出目前爲止沒有丟失請求
Reading:Nginx 讀取到客戶端的 Header 信息數
Writing:Nginx 返回給客戶端 Header 信息數
Waiting:Nginx 已經處理完正在等候下一次請求指令的駐留連接

7. ssl模塊配置

自生成證書
cd /etc/pki/CA
touch index.txt
echo 01 > serial
#生成CA自簽證書
(umask 077;openssl genrsa -out private/cakey.pem 2048)
openssl req -new -x509 -key private/cakey.pem -days 7300 -out cacert.pem
#生成證書
(umask 077;openssl genrsa -out /etc/nginx/ssl/nginx.key 2048)
openssl req -new -key /etc/nginx/ssl/nginx.key -days 365 -out /etc/nginx/ssl/nginx.csr
openssl ca -in /etc/nginx/ssl/nginx.csr -out /etc/nginx/ssl/nginx.crt -days 365
修改nginx配置文件

server {
        listen       443;                                                    #監聽端口爲443
        server_name  www.blpwdev.com
        ssl                  on;                    #開啓ssl
        ssl_certificate      /etc/nginx/ssl/nginx.crt;         #證書位置
        ssl_certificate_key  /etc/nginx/ssl/nginx.key;       #私鑰位置
        ssl_session_timeout  5m;                #紅色部分爲可選項
        ssl_protocols  SSLv2 SSLv3 TLSv1;        #指定密碼爲openssl支持的格式
        ssl_ciphers  HIGH:!aNULL:!MD5;              #密碼加密方式
        ssl_prefer_server_ciphers   on;               #依賴SSLv3和TLSv1協議的服務器密碼將優先於客戶端密碼
        location / {
            root   html;                        //根目錄的相對位置
            index  index.html index.htm;
        }
    }
server {
  listen 80;
        server_name  www.localhost.com;
        send_timeout 1800;
        rewrite ^(.*)$  https://$host$1 permanent;
}

8. auth basic認證模塊

auth basic
語法: auth_basic string | off;
默認值: auth_basic off;
配置段: http, server, location, limit_except
默認表示不開啓認證,後面若是跟上字符,這些字符會在彈窗中顯示
auth_basic_user_file
語法: auth_basic_user_file file;
默認值: —
配置段: http, server, location, limit_except
指定用戶密碼文件,使用htpasswd命令生成
nginx認證配置
建立用戶密碼文件
#htpasswd命令在httpd-devel包中,第一次建立用戶須要加-c選項
htpasswd -c /usr/local/nginx/conf/htpasswd test
#密碼生成也可使用openssl命令
printf 「test:$(openssl passwd -crypt 123456)\n」 >>/conf/htpasswd
在nginx配置文件中加入以下配置

server{
       server_name  www.blpwdev.com;
        index index.html index.htm;
        root html;       
        location /
        {
                auth_basic "nginx basic http test for localhost.com";
                auth_basic_user_file conf/htpasswd; 
#容許以列表格式顯示文件
                autoindex on;
        }
}

9. proxy_cache模塊

開啓緩存配置

proxy_cache_path  /data/proxy_cache_dir  levels=1:2   keys_zone=cache_one:200m inactive=1d max_size=30g use_temp_path=off;
server {
        listen 80;
        server_name www.localhost.com;
        access_log /var/log/nginx/student_access.log cache;
        error_log /var/log/nginx/student_error.log ;
        location ~ /purge(/.*) 
        {
            allow 127.0.0.1;
            deny all;
            proxy_cache_purge cache_one $host$1$is_args$args;
        }
        location ~ .*\.(gif|jpg|jpeg|png|bmp|ico|js|css)$ {
            proxy_cache cache_one;
            proxy_cache_valid  200 304 12h;
            proxy_cache_key $host$uri$is_args$args;
            #expires 30d;
            add_header X-Cache $upstream_cache_status;
            include /usr/local/nginx/vhost/proxy.configure;
            proxy_pass http://student_server;
        }
        location / {
            include /usr/local/nginx/vhost/proxy.configure;
            proxy_pass http://student_server;
        }
log_format  cache   '$remote_addr [$time_local] "$request" '
'"$upstream_status" $body_bytes_sent "$http_referer" '                         '"$http_user_agent" '
'"$upstream_addr" "$upstream_response_time" $upstream_cache_status';

#$upstream_cache_status 定義瀏覽器中的緩存狀態 HIT MISS EXPIRED
清除緩存
http://student.metasequoia.com/resource/images/login13.png #緩存
curl student.fcla***oom.com/purge/resource/images/login13.png #清除緩存
參數說明
/data/proxy_cache_dir:本地路徑,定義緩存資源的存放路徑
levels:定義緩存文件目錄層次
keys_zone:設置緩存名字和共享內存大小
inactive:未被訪問文件在緩存中保留時間
max_size:最大cache空間,不指定會用掉磁盤全部空間
use_temp_path:爲off會直接把緩存寫入cache文件中,不會使用temp_path
proxy_cache:啓動緩存,off表示關閉緩存
proxy_cache其它相關指定
proxy_no_cache: 定義知足條件的響應不會被緩存,其值有一個不爲空或0生效
proxy_cache_bypass: 定義哪些狀況不從cache讀取
proxy_cache_key: 給緩存數據定義一個鍵,在清除緩存用到
proxy_cache_methods: 定義緩存哪些http方法
proxy_cache_valid: 設置不一樣響應碼的緩存時間
proxy_cache_min_uses: 設置緩存的最小使用次數

10.upstream_check_module模塊

upstream配置

upstream xxxxxx{
    server 10.0.0.100:8080;
    server 10.0.0.101:8080;
    check interval=2000 rise=2 fall=2 timeout=1000 type=http;
    check_http_send "HEAD /check.txt HTTP/1.0\r\n\r\n";
    check_http_expect_alive http_2xx http_3xx http_4xx;
}

其中參數的定義以下:
interval:檢查的週期
fall:容許的檢查失敗次數,若失敗次數超過該值,則後端被標記爲"down"。
rise:檢查的成功次數達到該值,則後端被標記爲「up」。
timeout:檢查的超時時間。
type:後端檢查的協議類型(tcp|http)。
開啓狀態頁面

location /status {
          check_status;
          access_log   off;
            allow  127.0.0.1;
            deny all;
    }
相關文章
相關標籤/搜索