1. 程式人生 > 實用技巧 >Nginx-1.18.0的安裝配置與使用

Nginx-1.18.0的安裝配置與使用

一、安裝

1.1 yum安裝

(1) 配置好yum源與epel源

#本地光碟yum源
[development]
name=dvdbase repo
baseurl=file:///mnt/cdrom/
enabled=1
gpgcheck=1
gpgkey=file:///mnt/cdrom/RPM-GPG-KEY-CentOS-7

#線上阿里雲yum源
[aliyun]
name=aliyun repo
baseurl=https://mirrors.aliyun.com/centos/$releasever/os/$basearch/
enabled=1
gpgchedk=1
gpgkey=https://mirrors.aliyun.com/centos/$releasever/os/$basearch/RPM-GPG-KEY-CentOS-$releasever
#線上阿里雲EPEL源 [aliyunEpel] name=aliyun epel baseurl=https://mirrors.aliyun.com/epel/$releasever/$basearch enabled=1 gpgcheck=1 gpgkey=https://mirrors.aliyun.com/epel/RPM-GPG-KEY-EPEL-$releasever

(2) 安裝

[root@localhost ~]# yum install -y nginx

1.2 編譯安裝

(1) 下載安裝包

[root@localhost ~]# wget https://nginx.org/download/nginx-1.18.0.tar.gz

(2) 安裝相關依賴包

[root@localhost ~]# yum install -y gcc pcre-devel openssl-devel zlib-devel

(3) 建立nginx使用者,解壓原始碼包,開始編譯安裝

[root@localhost ~]# useradd -r -s /sbin/nologin nginx
[root@localhost ~]# tar -xf nginx-1.18.0.tar.gz 
[root@localhost ~]# cd nginx-1.18.0/
[root@localhost nginx-1.18.0]# ./configure --prefix=/usr/local/nginx \
> --user=nginx \ > --group=nginx \ > --with-http_ssl_module \ > --with-http_v2_module \ > --with-http_realip_module \ > --with-http_stub_status_module \ > --with-http_gzip_static_module \ > --with-pcre \ > --with-stream \ > --with-stream_ssl_module \ > --with-stream_realip_module [root@localhost nginx-1.18.0]# make && make install
./configure --prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module \
--with-http_gzip_static_module \
--with-pcre \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module
編譯程式碼

(4) 啟動nginx

#直接啟動
[root@localhost ~]# /usr/local/nginx/sbin/nginx
#或建立軟連結啟動
[root@localhost ~]# ln -s /usr/local/nginx/sbin/nginx /usr/sbin/
[root@localhost ~]# ll /usr/sbin/nginx 
lrwxrwxrwx 1 root root 27 Jun 17 11:42 /usr/sbin/nginx -> /usr/local/nginx/sbin/nginx
[root@localhost ~]# nginx

二、配置檔案詳解

#全域性配置端
user nginx nginx;                            #啟動Ngnix工作程序的使用者和組
worker_processes [number | auto];            #啟動的工作程序數
worker_cpu_affinity 0001 0010 0100 1000      #將Nginx工作程序繫結到指定的CPU核心,預設Nginx是不進行程序繫結的

error_log file [debug | info | notice | warn | error | crit | alert | emerg]    #錯誤日誌配置
#error_log logs/error.log;
#error_log logs/error.log notice;

pid    logs/nginx.pid;                       #pid檔案儲存路徑

work_priority 0;                             #工作程序的優先順序 -20~19
work_rlimit_nofile 65536;                    #工作程序最大開啟檔案數

daemon off|on;                                #前臺執行nginx用於測試,docker等環境,預設為on
master_process off|on;                        #是否開啟Nginx的master-woker工作模式,關閉後 nginx就不會fork出worker子程序來處理請求,而是以master程序自身來處理請求

events {                            #events設定塊
    worker_connections 1024;        #設定單個nginx工作程序可以接愛的最大併發連線資料;
                      ##在nginx作為http伺服器的時候,最大連線數為worker_processes * worker_connctions;在nginx作為反向代理伺服器的時候,最大連線數為worker_processes * worker_connections / 2 use epoll; #使用epoll事件驅動,Nginx支援眾多的事件驅動,比如select、poll、epoll,只能設定在events模組中設定 accept_mutex on; #優化同一時刻只有一個請求而避免多個睡眠程序被喚醒的設定,on為防止被同時喚醒預設為off,全部喚醒的過程也成為"驚群",因此nginx剛安裝完以後要進行適當的優化 multi_accept on; #Nginx伺服器的每個工作程序可以同時接受多個新的網路連線,但是需要在配置檔案中配置,此指令預設為關閉,即預設為一個工作程序只能一次接受一個新的網路連線,開啟後幾個同時接受多個 } http { #http設定塊 include mime.types; #匯入支援的檔案型別 default_type application/octet-stream; #設定預設的型別,會提示下載不匹配的型別檔案 #日誌配置部分 #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; #自定義優化引數 sendfile on; #指定是否使用sendfile系統呼叫來傳輸檔案 #tcp_nopush on; #在開啟了sendfile的情況下,合併請求後統一發送給客戶端 #tcp_nodelay off; #在開啟了keepalived模式下的連線是否啟用TCP_NODELAY選項,當為off時,延遲0.2s傳送,預設為on,不延遲傳送,立即傳送使用者相應報文 keepalive_timeout 65; #設定會話保持時間,單位是秒 #gzip on; #開啟檔案壓縮 server { listen 80; #設定監聽地址和埠 server_name localhost; #設定server name,可以以空格隔開寫多個,支援正則表示式,如 *.aaa.com,www.aaa.* ~^www\d+\.aaa\.com$ default_server #charset koi8-r; #設定編碼格式,預設是俄語格式,可以改為utf-8 #access_log logs/host.access.log main; #裝置訪問日誌 location / { root html; #指定網站目錄 index index.html index.htm; #指定預設網頁檔案,此指令由ngx_http_index_module模組提供 } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { #以http的方式轉發php請求到指定web伺服器 # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php$ { #以fastcgi的方式轉發php請求到php處理 # root html; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { #拒絕web形式訪問指定檔案,如很多的網站都是通過.htaccess檔案來改變自己的重定向等功能。 # deny all; #} } # another virtual host using mix of IP-, name-, and port-based configuration # #server { #自定義虛擬server # listen 8000; # listen somename:8080; # server_name somename alias another.alias; # location / { # root html; # index index.html index.htm; # } #} # HTTPS server # #server { #https伺服器配置 # listen 443 ssl; # server_name localhost; # ssl_certificate cert.pem; # ssl_certificate_key cert.key; # ssl_session_cache shared:SSL:1m; # ssl_session_timeout 5m; # ssl_ciphers HIGH:!aNULL:!MD5; # ssl_prefer_server_ciphers on; # location / { # root html; # index index.html index.htm; # } #} #include /usr/local/nginx/conf/conf.d/*.conf #匯入其他路徑的配置檔案 }

三、相關配置例項

3.1、站點基本配置

[root@localhost ~]# mkdir /usr/local/nginx/conf/conf.d
[root@localhost ~]# vim /usr/local/nginx/conf/conf.d/aaa.conf
server {
    listen 80;
    server_name www.aaa.com;

    location / {
        root html/aaa.com;
        index index.html index.htm
    }
}
[root@localhost ~]# mkdir /usr/local/nginx/html/aaa.com
[root@localhost ~]# echo "www.aaa.com" > /usr/local/nginx/html/aaa.com/index.html
[root@localhost ~]# nginx -s reload
[root@localhost ~]# curl www.aaa.com
www.aaa.com

3.2、root與alias

 root:指定web的家目錄,在定義location的時候,檔案的絕對路徑等於root+location,
 alias:定義路徑別名,會把訪問的路徑重新定義到其指定的路徑

#root
[root@localhost ~]# vim /usr/local/nginx/conf/conf.d/aaa.conf
server {
    listen 80;
    server_name www.aaa.com;

    location / {
        root html/aaa.com;
        index index.html index.htm;
    }
    location /about {
        root html/aaa.com;    #必須要在html/aaa.com目錄下建立一個about目錄才可以訪問,否則報錯
        index index.html index.htm;
    }
}
[root@localhost ~]# mkdir /usr/local/nginx/html/aaa.com/about
[root@localhost ~]# echo "about" > /usr/local/nginx/html/aaa.com/about/index.html
[root@localhost ~]# tree /usr/local/nginx/html/aaa.com/
/usr/local/nginx/html/aaa.com/
├── about
│ └── index.html
└── index.html
[root@localhost ~]# nginx -s reload
[root@localhost ~]# curl www.aaa.com/about/
about
#alias
[root@localhost ~]# vim /usr/local/nginx/conf/conf.d/aaa.conf 
server {
    listen 80;
    server_name www.aaa.com;

    location / {
        root html/aaa.com;
        index index.html index.htm;
    }
    location /about {              #使用alias的時候uri後面如果加了斜槓則下面的路徑配置必須加斜槓,否則403
        alias html/aaa.com;        #當訪問about的時候,會顯示alias定義的html/aaa.com裡面的內容
        index index.html index.htm;
    }
}
[root@localhost ~]# nginx -s reload
[root@localhost ~]# curl www.aaa.com/about/
www.aaa.com

3.3、location的匹配規則

語法規則: location [=|~|~*|^~] /uri/ { … }
=      #用於標準uri前,需要請求字串與uri精確匹配,如果匹配成功就停止
~      #用於標準uri前,表示包含正則表示式並且區分大小寫
~*     #用於標準uri前,表示包含正則表示式並且不區分大寫
!~     #用於標準uri前,表示包含正則表示式並且區分大小寫不匹配
!~*   #用於標準uri前,表示包含正則表示式並且不區分大小寫不匹配
^~    #用於標準uri前,表示包含正則表示式並且匹配以什麼開頭
$     #用於標準uri前,表示包含正則表示式並且匹配以什麼結尾
\     #用於標準uri前,表示包含正則表示式並且轉義字元。可以轉. * ?*     #用於標準uri前,表示包含正則表示式並且代表任意長度的任意字元

匹配優先順序:=, ^~, ~/~*,/
location優先順序:(location =) > (location 完整路徑) > (location ^~ 路徑) > (location ~,~* 正則順序) > (location 部分起始路徑) > (/)

location = /1.jpg {          #只能訪問1.jpg
    root html/aaa.com/images;
    index index.html;
}

location ~ /A.?\.jpg {        #只能訪問Ax.jpg,x表示任一單個字元
    root html/aaa.com/images;
    index index.html;
}

location ~* /A.?\.jpg {       #可以訪問Ax.jpg或Ax.JPG,x表示任一單個字元
    root html/aaa.com/images;
    index index.html;
}

location ^~ /images {         #匹配以images開頭
    root html/aaa.com/images;
    index index.html;
}

location ~* \.(gif|jpg|jpeg|bmp|png|tiff|tif|ico|wmf|js)$ {        #匹配結尾
    root html/aaa.com/images;
    index index.html;
}

3.4、Nginx 四層訪問控制

location /about {
    alias /data/nginx/html/pc;
    index index.html;
    deny 192.168.145.1;
    allow 192.168.145.0/24;
    allow 2001:0db8::/32;
    deny all;             #先允許小部分,再拒絕大部分
}        

3.5、Nginx賬戶認證功能

[root@localhost ~]# yum install -y httpd-tools
[root@localhost ~]# htpasswd -cbm /usr/local/nginx/conf/.htpasswd user1 123456
Adding password for user user1
[root@localhost ~]# htpasswd -bm /usr/local/nginx/conf/.htpasswd user2 123456
Adding password for user user2
[root@localhost ~]# tail /usr/local/nginx/conf/.htpasswd 
user1:$apr1$jsO6E/ci$xvL4zCDCnH28SXoY00MjQ0
user2:$apr1$k00UYYEp$UKi8pQKdfPtQQplgLsxyF/
[root@localhost ~]# vim /usr/local/nginx/conf/conf.d/aaa.conf 
server {
    listen 80;
    server_name www.aaa.com;

    location / {
        root html/aaa.com;
        index index.html index.htm;
    }
    location /about {
        root html/aaa.com;
        index index.html index.htm;
        auth_basic "login password";
        auth_basic_user_file /usr/local/nginx/conf/.htpasswd;
    }
}

3.6、自定義錯誤頁面

[root@localhost ~]# cat  /usr/local/nginx/html/error.html
Sorry,This is a error page.
[root@localhost ~]# vim /usr/local/nginx/conf/conf.d/aaa.conf 
server {
    listen 80;
    server_name www.aaa.com;
    error_page 500 502 503 504 404 /error.html

    location / {
        root html/aaa.com;
        index index.html index.htm;
    }
    location /error.html {
        root html;
    }
}

3.7、自定義訪問日誌

[root@localhost ~]# vim /usr/local/nginx/conf/conf.d/aaa.conf 
server {
    listen 80;
    server_name www.aaa.com;
    error_page 500 502 503 504 404 /error.html;
    access_log logs/www.aaa.com_access.log;
    error_log logs/www.aaa.com_error.log;
    location / {
        root html/aaa.com;
        index index.html index.htm;
    }
    location = /error.html {
        root html;
    }
}

3.8、檢測檔案是否存在

 try_files會按順序檢查檔案是否存在,返回第一個找到的檔案或資料夾(結尾加斜線表示為資料夾),如果所有檔案或資料夾都找不到,會進行一個內部重定向到最後一個引數。只有最後一個引數可以引起一個內部重定向,之前的引數只設置內部URI的指向。最後一個引數是回退URI且必須存在,否則會出現內部500錯誤。

location /about {
    root html/aaa.com;
    index index.html index.htm;
    #try_files $uri $uri/index.html $uri.html /about/default.html;
    try_files $uri $uri/index.html $uri.html =489;
}
#當訪問到不存在的uri會顯示default.html,如果是自定義的狀態碼則會顯示在返回資料的狀態碼中,如
[root@localhost ~]# curl www.aaa.com/about/xx.html
default page
[root@localhost ~]# curl --head www.aaa.com/about/xx.html 
HTTP/1.1 489 
Server: nginx/1.18.0
Date: Wed, 17 Jun 2020 09:49:00 GMT
Content-Length: 0
Connection: keep-alive

3.9、長連線配置

keepalive_timeout number;  #設定保持連線超時時長,0表示禁止長連線,預設為75s,通常配置在http欄位作為站點全域性配置
keepalive_requests number; #在一次長連線上所允許請求的資源的最大數量,預設為100次
keepalive_requests
3; keepalive_timeout 60 60; #開啟長連線後,返回客戶端的會話保持時間為60s,單次長連線累計請求達到指定次數請求或65秒就會被斷開,後面的60為傳送給客戶端應答報文頭部中顯示的超時時間設定為60s:如不設定客戶端將不顯示超時時間。 Keep-Alive:timeout=60   #瀏覽器收到的伺服器返回的報文 #如果設定為0表示關閉會話保持功能,將如下顯示: Connection:close      #瀏覽器收到的伺服器返回的報文

3.10、作為下載伺服器配置

[root@localhost ~]# vim /usr/local/nginx/conf/conf.d/aaa.conf
server {
    listen 80;
    server_name www.aaa.com;
    location / {
        root html/aaa.com;
        index index.html index.htm;
    }
    location /download {
        root html/aaa.com;
        autoindex on;
        autoindex_exact_size on;
        autoindex_localtime on;
    }
}
[root@localhost ~]# mkdir /usr/local/nginx/html/aaa.com/download
[root@localhost ~]# cp nginx-1.18.0.tar.gz /usr/local/nginx/html/aaa.com/download/
#瀏覽器訪問 www.aaa.com/download 測試

3.11、作為上傳伺服器

client_max_body_size 1m;          #設定允許客戶端上傳單個檔案的最大值,預設值為1m
client_body_buffer_size size;      #用於接收每個客戶端請求報文的body部分的緩衝區大小;預設16k;超出此大小時,其將被暫存到磁碟上的由下面client_body_temp_path指令所定義的位置
client_body_temp_path path [level1 [level2 [level3]]];        #設定儲存客戶端請求報文的body部分的臨時儲存路徑及子目錄結構和數量,目錄名為16進位制的數字,使用hash之後的值從後往前擷取1位、2位、2位作為檔名
配置示例: client_max_body_size 10m; client_body_buffer_size 16k; client_body_temp_path
/usr/local/nginx/temp 1 2 2; #reload Nginx會自動建立temp目錄

3.12、隱藏Nginx Server版本資訊

server_tokens off;        #隱藏Nginx server版本

3.13、其它配置項

keepalive_disable none | browser ...;          #對哪種瀏覽器禁用長連線
limit_except method ... { ... }                 #僅用於location限制客戶端使用除了指定的請求方法之外的其它方法
    method:GET, HEAD, POST, PUT, DELETE,MKCOL, COPY, MOVE, OPTIONS, PROPFIND,ROPPATCH, LOCK, UNLOCK, PATCH
    limit_except GET {
        allow 192.168.0.0/24;
        allow 192.168.7.101;
        deny all;
    }
aio on
| off #是否啟用asynchronous file I/O(AIO)功能,需要編譯開啟 linux 2.6以上核心提供以下幾個系統呼叫來支援aio: 1、SYS_io_setup:建立aio 的context 2、SYS_io_submit: 提交I/O操作請求 3、SYS_io_getevents:獲取已完成的I/O事件 4、SYS_io_cancel:取消I/O操作請求 5、SYS_io_destroy:毀銷aio的context directio size | off;        #操作完全和aio相反,aio是讀取檔案而directio是寫檔案到磁碟,啟用直接I/O,預設為關閉,當檔案大於等於給定大小時,例如directio 4m,同步(直接)寫磁碟,而非寫快取。
open_file_cache off; #是否快取開啟過的檔案資訊 open_file_cache max
=N [inactive=time]; nginx可以快取以下三種資訊: (1) 檔案元資料:檔案的描述符、檔案大小和最近一次的修改時間 (2) 開啟的目錄結構 (3) 沒有找到的或者沒有許可權訪問的檔案的相關資訊 max=N:可快取的快取項上限數量;達到上限後會使用LRU(Least recently used,最近最少使用)演算法實現管理 inactive=time:快取項的非活動時長,在此處指定的時長內未被命中的或命中的次數少於open_file_cache_min_uses指令所指定的次數的快取項即為非活動項,將被刪除 open_file_cache_min_uses number; #open_file_cache指令的inactive引數指定的時長內,至少被命中此處指定的次數方可被歸類為活動項,預設值為1 open_file_cache_errors on | off;    #是否快取查詢時發生錯誤的檔案一類的資訊,預設值為off open_file_cache_valid time; #快取項有效性的檢查驗證頻率,預設值為60s #配置例項: open_file_cache max=10000 inactive=60s;   #最大快取10000個檔案,非活動資料超時時長60s open_file_cache_valid 60s; #每間隔60s檢查一下快取資料有效性 open_file_cache_min_uses 5;   #60秒內至少被命中訪問5次才被標記為活動資料 open_file_cache_errors on; #快取錯誤資訊

四、高階應用

4.1、狀態頁配置

 基於nginx模組ngx_http_auth_basic_module實現,在編譯安裝nginx的時候需要新增編譯引數--with-http_stub_status_module,否則配置完成之後監測會是提示語法錯誤。

location /nginx_status {
    stub_status;
    allow 192.168.145.0/24;
    allow 127.0.0.1;
    deny all;
}
[root@www ~]# curl 192.168.145.27/nginx_status/
Active connections: 4 
server accepts handled requests
 13 13 28 
Reading: 0 Writing: 1 Waiting: 3

Active connections:     當前處於活動狀態的客戶端連線數,包括連線等待空閒連線數。
accepts:                統計總值,Nginx自啟動後已經接受的客戶端請求的總數。
handled:                統計總值,Nginx自啟動後已經處理完成的客戶端請求的總數,通常等於accepts,除非有因worker_connections限制等被拒絕的連線。
requests:               統計總值,Nginx自啟動後客戶端發來的總的請求數。
Reading:                當前狀態,正在讀取客戶端請求報文首部的連線的連線數。
Writing:                當前狀態,正在向客戶端傳送響應報文過程中的連線數。
Waiting:                當前狀態,正在等待客戶端發出請求的空閒連線數,開啟 keep-alive的情況下,這個值等於active – (reading+writing)

4.2、變數使用

 Nginx的變數可以在配置檔案中引用,作為功能判斷或者日誌等場景使用,變數可以分為內建變數和自定義變數,內建變數是由nginx模組自帶,通過變數可以獲取到眾多的與客戶端訪問相關的值。

 (1) 內建變數

$remote_addr;        #存放了客戶端的地址,注意是客戶端的公網IP,也就是一家人訪問一個網站,則會顯示為路由器的公網IP
$args;               #變數中存放了URL中的指令,例如http://www.aaa.com/about/index.do?id=202006&partner=search中的id=202006&partner=search
$document_root;     #儲存了針對當前資源的請求的系統根目錄,如/usr/local/nginx/html
$document_uri;       #儲存了當前請求中不包含指令的URI,注意是不包含請求的指令,例如http://www.aaa.com/about/index.do?id=202006&partner=search中的/about/index.do
$host;               #存放了請求的host名稱。
$http_user_agent;    #客戶端瀏覽器的詳細資訊
$http_cookie;        #客戶端的cookie資訊。

limit_rate 10240;
echo $limit_rate;    #如果nginx伺服器使用limit_rate配置了顯示網路速率,則會顯示,如果沒有設定, 則顯示0。
$remote_port;      #客戶端請求Nginx伺服器時隨機開啟的埠,這是每個客戶端自己的埠。
$remote_user;      #已經經過Auth Basic Module驗證的使用者名稱。
$request_body_file;    #做反向代理時發給後端伺服器的本地資源的名稱。
$request_method;       #請求資源的方式,GET/PUT/DELETE等
$request_filename;     #當前請求的資原始檔的路徑名稱,由root或alias指令與URI請求生成的檔案絕對路徑,如/apps/nginx/html/main/index.html
$request_uri;          #包含請求引數的原始URI,不包含主機名,如:/main/index.do?id=20190221&partner=search 。
$scheme;            #請求的協議,如ftp,https,http等。
$server_protocol;     #儲存了客戶端請求資源使用的協議的版本,如HTTP/1.0,HTTP/1.1,HTTP/2.0等。
$server_addr;       #儲存了伺服器的IP地址。
$server_name;         #請求的伺服器的主機名。

 (2) 自定義變數

  假如需要自定義變數名稱和值,使用指令set $variable value;,則方法如下:

  Syntax: set $variable value;

  Default: —

  Context: server, location, if

set $name aaa;
echo $name;
set $my_port $server_port;
echo $my_port;
echo "$server_name:$server_port";

4.3、壓縮功能

 Nginx支援對指定型別的檔案進行壓縮然後再傳輸給客戶端,而且壓縮還可以設定壓縮比例,壓縮後的檔案大小將比原始檔顯著變小,這樣有助於降低出口頻寬的利用率,降低企業的IT支出,不過會佔用相應的CPU資源。Nginx對檔案的壓縮功能是依賴於模組ngx_http_gzip_module。

#相關配置引數:
gzip on | off;                #啟用或禁用gzip壓縮,預設關閉
gzip_comp_level level;        #壓縮比由低到高從1到9,預設為1
gzip_disable "MSIE [1-6]\.";  #禁用IE6 gzip功能
gzip_min_length 1k;           #gzip壓縮的最小檔案,小於設定值的檔案將不會壓縮
gzip_http_version 1.0 | 1.1;  #啟用壓縮功能時,協議的最小版本,預設HTTP/1.1
gzip_buffers number size;     #指定Nginx服務需要向伺服器申請的快取空間的個數*大小,預設32 4k|16 8k;
gzip_types mime-type ...;     #指明僅對哪些型別的資源執行壓縮操作;預設為gzip_types text/html,不用顯示指定,否則出錯
gzip_vary on | off;           #如果啟用壓縮,是否在響應報文首部插入"Vary: Accept-Encoding"
如:
gzip on;
gzip_comp_level 5;
gzip_min_length 1k;
gzip_types text/plain application/javascript application/x-javascripttext/css application/xml text/javascript application/x-httpd-php image/jpegimage/gif image/png;
gzip_vary on

4.4、https配置

 Nginx 的https功能基於模組ngx_http_ssl_module實現,因此如果是編譯安裝的nginx要使用引數ngx_http_ssl_module開啟ssl功能,但是作為nginx的核心功能,yum安裝的nginx預設就是開啟的,編譯安裝的nginx需要指定編譯引數--with-http_ssl_module開啟。

ssl on | off;                  #為指定的虛擬主機配置是否啟用ssl功能,此功能在1.15.0廢棄,使用listen [ssl]替代。
ssl_certificate /path/to/file;        #當前虛擬主機使用使用的公鑰檔案,一般是crt檔案
ssl_certificate_key /path/to/file;    #當前虛擬主機使用的私鑰檔案,一般是key檔案
ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];    #支援ssl協議版本,早期為ssl現在是TSL,預設為後三個
ssl_session_cache off | none | [builtin[:size]] [shared:name:size];        #配置ssl快取
    off: 關閉快取
    none: 通知客戶端支援ssl session cache,但實際不支援
    builtin[:size]:使用OpenSSL內建快取,為每worker程序私有
    [shared:name:size]:在各worker之間使用一個共享的快取,需要定義一個快取名稱和快取空間大小,一兆可以儲存4000個會話資訊,多個虛擬主機可以使用相同的快取名稱。
    ssl_session_timeout time;#客戶端連線可以複用ssl session cache中快取的有效時長,預設5m

 #nginx證書配置
 listen 80;
 listen 443 ssl;
 ssl_certificate /usr/local/nginx/certs/www.aaa.com.crt;
 ssl_certificate_key /usr/local/nginx/certs/www.aaa.com.key;
 ssl_session_cache shared:sslcache:20m;
 ssl_session_timeout 10m;

#自簽名CA證書
[root@www ~]# cd /usr/local/nginx/
[root@www nginx]# mkdir certs
[root@www nginx]# cd certs/
[root@www certs]# openssl req -newkey rsa:4096 -nodes -sha256 -keyout ca.key -x509 -days 365 -out ca.crt
Generating a 4096 bit RSA private key
..............................................................................................................................................................................................................++
.............................................................................................................++
writing new private key to 'ca.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN  #國家
State or Province Name (full name) []:GD    #省份
Locality Name (eg, city) [Default City]:SZ    #城市
Organization Name (eg, company) [Default Company Ltd]:tech.Ltd   #公司名稱
Organizational Unit Name (eg, section) []:ops    #部門
Common Name (eg, your name or your server's hostname) []:aaa.com    #通用名稱
Email Address []:43112211@qq.com    #郵箱
[root@www certs]# ll
total 8
-rw-r--r-- 1 root root 2065 Jun 18 15:46 ca.crt
-rw-r--r-- 1 root root 3272 Jun 18 15:46 ca.key
#自制key和csr檔案
[root@www certs]# openssl req -newkey rsa:4096 -nodes -sha256 -keyout www.aaa.com.key -out www.aaa.com.csr
Generating a 4096 bit RSA private key
..............................................++
..++
writing new private key to 'www.aaa.com.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:GD
Locality Name (eg, city) [Default City]:SZ
Organization Name (eg, company) [Default Company Ltd]:tech.Ltd
Organizational Unit Name (eg, section) []:ops
Common Name (eg, your name or your server's hostname) []:www.aaa.com
Email Address []:43112211@qq.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@www certs]# ll
total 16
-rw-r--r-- 1 root root 2065 Jun 18 15:46 ca.crt
-rw-r--r-- 1 root root 3272 Jun 18 15:46 ca.key
-rw-r--r-- 1 root root 1728 Jun 18 15:49 www.aaa.com.csr
-rw-r--r-- 1 root root 3268 Jun 18 15:49 www.aaa.com.key
#簽發證書
[root@www certs]# openssl x509 -req -days 365 -in www.aaa.com.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out www.aaa.com.crt
Signature ok
subject=/C=CN/ST=GD/L=SZ/O=tech.Ltd/OU=ops/CN=www.aaa.com/emailAddress=43112211@qq.com
Getting CA Private Key
#檢視證書內容
[root@www certs]# openssl x509 -in www.aaa.com.crt -noout -text
Certificate:
    Data:
        Version: 1 (0x0)
        Serial Number:
            c4:6b:f1:61:33:25:43:9b
    Signature Algorithm: sha256WithRSAEncryption
        Issuer: C=CN, ST=GD, L=SZ, O=tech.Ltd, OU=ops, CN=aaa.com/emailAddress=43112211@qq.com
        Validity
            Not Before: Jun 18 07:50:31 2020 GMT
            Not After : Jun 18 07:50:31 2021 GMT
        Subject: C=CN, ST=GD, L=SZ, O=tech.Ltd, OU=ops, CN=www.aaa.com/emailAddress=43112211@qq.com
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (4096 bit)
                .....
實現過程

4.5、關於favicon.ico

 favicon.ico 檔案是瀏覽器收藏網址時顯示的圖示,當客戶端使用瀏覽器問頁面時,瀏覽器會自己主動發起請求獲取頁面的favicon.ico檔案,但是當瀏覽器請求的favicon.ico檔案不存在時,伺服器會記錄404日誌,而且瀏覽器也會顯示404報錯。

#解決辦法:
#1.伺服器不記錄訪問日誌:
location = /favicon.ico {
    log_not_found off;
    access_log off;
}
#2.將圖示儲存到指定目錄訪問:
#location ~ ^/favicon\.ico$ {
location = /favicon.ico {
    root /data/nginx/html/pc/images;
}

4.6、rewrite指令

 通過正則表示式的匹配來改變URI,可以同時存在一個或多個指令,按照順序依次對URI進行匹配,rewrite主要是針對使用者請求的URL或者是URI做具體處理。

 用法:rewrite regex replacement [flag];

 (1) rewrite flag

  利用nginx的rewrite的指令,可以實現url的重新跳轉,rewrtie有四種不同的flag,分別是redirect(臨時重定向)、permanent(永久重定向)、break和last。其中前兩種是跳轉型的flag,後兩種是代理型,跳轉型是指有客戶端瀏覽器重新對新地址進行請求,代理型是在WEB伺服器內部實現跳轉的。

redirect;         #臨時重定向,重寫完成後以臨時重定向方式直接返回重寫後生成的新URL給客戶端,由客戶端重新發起請求;使用相對路徑,或者http://或https://開頭,狀態碼:302
permanent;        #重寫完成後以永久重定向方式直接返回重寫後生成的新URL給客戶端,由客戶端重新發起請求,狀態碼:301
last;             #重寫完成後停止對當前URI在當前location中後續的其它重寫操作,而後對新的URL啟動新一輪重寫檢查,不建議在location中使用
break;            #重寫完成後停止對當前URL在當前location中後續的其它重寫操作,而後直接跳轉至重寫規則配置塊之後的其它配置;結束迴圈,建議在location中使用

 (2) 臨時重定向與永久重定向

location / {
    root /usr/local/nginx/html/pc;
    index index.html;
    rewrite / http://www.aaa.com permanent;
    #rewrite / http://www.aaa.com redirect;
}

 (3) last與break

location /break {
    rewrite ^/break/(.*) /test$1 break;        #break不會跳轉到其他的location
    return 666 "break";
}

location /last {
    rewrite ^/last/(.*) /test$1 last;        #last會跳轉到其他的location繼續匹配新的URI
    return 888 "last";
}

location /test {
    return 999 "test";
}

 (4) 自動跳轉https

server {
    listen 80;
    listen 443 ssl;
    ssl_certificate /usr/local/nginx/certs/www.aaa.com.crt;
    ssl_certificate_key /usr/local/nginx/certs/www.aaa.com.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;
    server_name www.aaa.com;
    location / {
        root html/aaa.com;
        index index.html index.htm;
        if ($scheme = http){    #不加條件判斷,會導致死迴圈
            rewrite / https://www.aaa.com permanent;
        }
    }
}

#還一種是對監聽的80埠進行跳轉
server {
    listen 80 default_server;
    server_name www.aaa.com;
    rewrite ^(.*)$ https://$server_name$1 permanent;
}

 (5) 判斷檔案是否存在

例:當用戶訪問到公司網站的時輸入了一個錯誤的URL,可以將使用者重定向至官網首頁
location / {
    root /usr/local/nginx/html/pc;
    index index.html;
    if (!-f $request_filename) {
        #return 404 "No Page";
        rewrite (.*) http://www.aaa.net/index.html;
    }
}

 (6) 防盜鏈

  防盜鏈基於客戶端攜帶的referer實現,referer是記錄開啟一個頁面之前記錄是從哪個頁面跳轉過來的標記資訊,如果別人只連結了自己網站圖片或某個單獨的資源,而不是打開了網站的整個頁面,這就是盜鏈,referer就是之前的那個網站域名,正常的referer資訊有以下幾種:

none:              #請求報文首部沒有referer首部,比如使用者直接在瀏覽器輸入域名訪問web網站,就沒有referer資訊。
blocked:           #請求報文有referer首部,但無有效值,比如為空。
server_names:      #referer首部中包含本主機名及即nginx 監聽的server_name。
arbitrary_string:   #自定義指定字串,可使用*作萬用字元。
regular expression: #被指定的正則表示式模式匹配到的字串,要使用~開頭,例如:~.*\.aaa\.com
location ^~ /images {
    root /usr/local/nginx/pc;
    index index.html;
    valid_referers none blocked server_names *.aaa.com www.aaa.* api.online.test/v1/hostlist ~\.google\. ~\.baidu\.;                 #定義有效的referer
    if ($invalid_referer) {        #假如是使用其他的無效的referer訪問:
        return 403;             #返回狀態碼403
    }
}

4.7、代理功能

 Nginx除了可以在企業提供高效能的web服務之外,另外還可以將本身不具備的請求通過某種預定義的協議轉發至其它伺服器處理,不同的協議就是Nginx伺服器與其他伺服器進行通訊的一種規範,主要在不同的場景使用以下模組實現不同的功能:

  ngx_http_proxy_module:   將客戶端的請求以http協議轉發至指定伺服器進行處理。
  ngx_stream_proxy_module: 將客戶端的請求以tcp協議轉發至指定伺服器處理。
  ngx_http_fastcgi_module:  將客戶端對php的請求以fastcgi協議轉發至指定伺服器助理。
  ngx_http_uwsgi_module:  將客戶端對Python的請求以uwsgi協議轉發至指定伺服器處理。

 配置引數:
  proxy_pass; #用來設定將客戶端請求轉發給的後端伺服器的主機,可以是主機名、IP地址:埠的方式,也可以代理到預先設定的主機群組;

location /web {
    index index.html;
    proxy_pass http://192.168.7.103:80;
    #不帶斜線將訪問的/web,等於訪問後端伺服器 http://192.168.7.103:80/web/index.html,即後端伺服器配置的站點根目錄要有web目錄才可以被訪問,這是一個追加/web到後端伺服器 http://servername:port/WEB/INDEX.HTML的操作
    proxy_pass http://192.168.7.103:80/;    #帶斜線,等於訪問後端伺服器的http://192.168.7.103:80/index.html 內容返回給客戶端
}

 (1) 正向代理配置

#代理伺服器上配置
http {
    resolver 8.8.8.8;
    server {
        listen 8088;
        location / {
            proxy_pass http://$http_host$request_uri;
        }
    }
}
#客戶端配置
export "http_proxy=http://[user]:[pass]@host:port/"
如:export http_proxy=http://192.168.145.27:8088

 (2) 反向代理配置

server {
    listen 80;
    server_name www.magedu.net;
    location / {
        proxy_pass http://192.168.145.7:80/;
    }
}
#也可以對指定location進行代理
location /web {
    proxy_pass http://192.168.7.103:80/;     #注意有後面的/
}

 (3) 代理快取功能

#代理快取功能預設關閉,可通過下面引數配置:
proxy_cache zone | off;           #指明呼叫的快取,或關閉快取機制;預設off;Context:http, server, location
proxy_cache_key string;            #快取中用於"鍵"的內容,預設值:proxy_cache_key $scheme$proxy_host$request_uri;
proxy_cache_valid [code ...]
time; #定義對特定響應碼的響應內容的快取時長,定義在http{...}中
示例: proxy_cache_valid
200 302 10m; proxy_cache_valid 404 1m; proxy_cache_path; #定義可用於proxy功能的快取;Context:http proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time]
[purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time]; 例:在http配置定義快取資訊 proxy_cache_path /var/cache/nginx/proxy_cache #定義快取儲存路徑,proxy_cache會自動建立 levels=1:2:2 #定義快取目錄結構層次,1:2:2可以生成2^4x2^8x2^8=1048576個目錄 keys_zone=proxycache:20m #指記憶體中快取的大小,主要用於存放key和metadata(如:使用次數) inactive=120s #快取有效時間 max_size=1g; #最大磁碟佔用空間,磁碟存入檔案內容的快取空間最大值
#呼叫快取功能,需要定義在相應的配置段,如server{...};或者location等 proxy_cache proxycache; proxy_cache_key $request_uri; proxy_cache_valid
200 302 301 1h; proxy_cache_valid any 1m; proxy_cache_use_stale;    #在被代理的後端伺服器出現哪種情況下,可直接使用過期的快取響應客戶端 proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 | http_503 | http_504 | http_403 | http_404 | off ;   #預設是off proxy_cache_methods GET | HEAD | POST ...; #對哪些客戶端請求方法對應的響應進行快取,GET和HEAD方法總是被快取 proxy_set_header field value; #設定發往後端主機的請求報文的請求首部的值 Context: http, server, location proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 請求報文的標準格式如下: X-Forwarded-For: client1, proxy1, proxy2 [root@www ~]# vim /usr/local/nginx/conf/nginx.conf #配置在nginx.conf http配置段 proxy_cache_path /usr/local/nginx/proxycache levels=1:1:1 keys_zone=proxycache:20m inactive=120s max_size=1g; [root@www ~]# vim /usr/local/nginx/conf/conf.d/pc.conf #要快取的URL 或者放在server配置項對所有URL都進行快取 location /web { proxy_pass http://192.168.27.7:80/; proxy_set_header clientip $remote_addr; proxy_cache proxycache; proxy_cache_key $request_uri; proxy_cache_valid 200 302 301 1h; proxy_cache_valid any 1m; }

 (4) 新增頭部報文資訊

  Syntax: add_header name value [always];
  Default: —
  Context: http, server, location, if in location

#新增自定義首部
add_header name value [always];
add_header X-Via $server_addr;
add_header X-Cache $upstream_cache_status;
add_header X-Accel $server_name;

#新增自定義響應資訊的尾部, 1.13.2版後支援
add_trailer name value [always];

#nginx配置:
location /web {
    proxy_pass http://192.168.27.7:80/;
    proxy_set_header clientip $remote_addr;
    proxy_cache proxycache;
    proxy_cache_key $request_uri;
    proxy_cache_valid 200 302 301 1h;
    proxy_cache_valid any 1m;
    add_header X-Via $server_addr;
    add_header X-Cache $upstream_cache_status;
    add_header X-Accel $server_name;
}

4.8、負載均衡

 (1) http的負載均衡-upstream

配置引數:
upstream name {        #自定義一組伺服器,配置在http內
    server address [parameters];    #配置一個後端web伺服器,配置在upstream內,至少要有一個server伺服器配置。
}
#server支援的parameters如下: weight
=number #設定權重,預設為1 max_conns=number #給當前server設定最大活動連結數,預設為0表示沒有限制 max_fails=number #對後端伺服器連續監測失敗多少次就標記為不可用 fail_timeout=time #對後端伺服器的單次監測超時時間,預設為10秒 backup #設定為備份伺服器,當所有伺服器不可用時將重新啟用次伺服器 down #標記為down狀態 resolve #當server定義的是主機名的時候,當A記錄發生變化會自動應用新IP而不用重啟Nginx hash KEY consistent; #基於指定key做hash計算,使用consistent引數,將使用ketama一致性hash演算法,適用於後端是Cache伺服器(如varnish)時使用,consistent定義使用一致性hash運算,一致性hash基於取模運算。所謂取模運算,就是計算兩個數相除之後的餘數,比如10%7=3, 7%4=3 hash $request_uri consistent; #基於使用者請求的uri做hash ip_hash; #源地址hash排程方法,基於的客戶端的remote_addr(源地址)做hash計算,以實現會話保持
排程演算法:
    rr:         輪詢,預設的排程方式,將所有請求都按照時間順序分配到不同的服務上;
    weight:      權重,指定每個服務的權重比例,weight和訪問比率成正比;
    ip_hash:     指定負載均衡器按照基於客戶端IP的分配方式,這個方法確保了相同的客戶端的請求一直髮送到相同的伺服器,以保證session會話。這樣每個訪客都固定訪問一個後端伺服器,可以解決session不能跨伺服器的問題;
    least_conn:  把請求轉發給連線數較少的後端伺服器。輪詢演算法是把請求平均的轉發給各個後端,使它們的負載大致相同;但是,有些請求佔用的時間很長,會導致其所在的後端負載較高。這種情況下,least_conn這種方式就可以達到更好的負載均衡效果
    fair:      按照伺服器端的響應時間來分配請求,響應時間短的優先分配;
    url_hash:   按訪問url的hash結果來分配請求,使每個url定向到同一個後端伺服器,要配合快取命中來使用。同一個資源多次請求,可能會到達不同的伺服器上,導致不必要的多次下載,快取命中率不高,以及一些資源時間的浪費;
            而使用url_hash,可以使得同一個url(也就是同一個資源請求)會到達同一臺伺服器,一旦快取住了資源,再此收到請求,就可以從快取中讀取; 例: upstream webserver { #hash $request_uri consistent; #ip_hash; #least_conn; server
192.168.27.7:80 weight=1 fail_timeout=5s max_fails=3; #後端伺服器狀態監測 server 192.168.27.17:80 weight=1 fail_timeout=5s max_fails=3 backup; } server { listen 80; server_name www.aaa.net; location / { index index.html index.php; root /usr/local/nginx/html/pc; } location /web { index index.html; proxy_pass http://webserver/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #客戶端IP透傳,新增客戶端IP到報文頭部 } }

 (2) tcp的負載均衡

  Nginx在1.9.0版本開始支援tcp模式的負載均衡,在1.9.13版本開始支援udp協議的負載,udp主要用於DNS的域名解析,其配置方式和指令和http代理類似,其基於ngx_stream_proxy_module模組實現tcp負載,另外基於模組ngx_stream_upstream_module實現後端。

配置引數:
stream {         #定義stream
    upstream backend {                        #定義後端伺服器
        hash $remote_addr consistent;         #定義排程演算法
        server backend1.example.com:12345 weight=5;         #定義具體server
        server 127.0.0.1:12345 max_fails=3 fail_timeout=30s;
        server unix:/tmp/backend3;
    }
    upstream dns {                            #定義後端伺服器
        server 192.168.0.1:53535;             #定義具體server
        server dns.example.com:53;
    }
    server {                                  #定義server
        listen 12345;                         #監聽IP:PORT
        proxy_connect_timeout 1s;             #連線超時時間
        proxy_timeout 3s;                     #轉發超時時間
        proxy_pass backend;                   #轉發到具體伺服器組
    }
    server {
        listen 127.0.0.1:53 udp reuseport;
        proxy_timeout 20s;
        proxy_pass dns;
    }
    server {
        listen [::1]:12345;
        proxy_pass unix:/tmp/stream.socket;
    }
}
例項1:Redis負載均衡 stream { upstream redis_server { #hash $remote_addr consistent; server
192.168.145.27:6379 max_fails=3 fail_timeout=30s; } server { listen 192.168.145.7:6379; proxy_connect_timeout 3s; proxy_timeout 3s; proxy_pass redis_server; } } 例項2:mysql負載均衡 stream { upstream mysql_server { least_conn; server 192.168.145.27:3306 max_fails=3 fail_timeout=30s; } server { listen 192.168.145.7:3306; proxy_connect_timeout 6s; proxy_timeout 15s; proxy_pass mysql_server; } }

4.9、FastCGI配置

 Nginx基於模組ngx_http_fastcgi_module實現通過fastcgi協議將指定的客戶端請求轉發至php-fpm處理,其配置引數如下:

fastcgi_pass address;        #轉發請求到後端伺服器,address為後端的fastcgi server的地址,可用位置:location, if in location 
fastcgi_index name;            #fastcgi預設的主頁資源,示例:fastcgi_index index.php;
fastcgi_param parameter value [if_not_empty];        #設定傳遞給FastCGI伺服器的引數值,可以是文字,變數或組合,可用於將Nginx的內建變數賦值給自定義key
fastcgi_param REMOTE_ADDR $remote_addr;     #客戶端源IP
fastcgi_param REMOTE_PORT $remote_port;     #客戶端源埠
fastcgi_param SERVER_ADDR $server_addr;     #請求的伺服器IP地址
fastcgi_param SERVER_PORT $server_port;     #請求的伺服器埠
fastcgi_param SERVER_NAME $server_name;     #請求的server name
Nginx預設配置示例:
location ~ \.php$ {
    root html;        #$document_root 呼叫root目錄
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;     #預設指令碼路徑
    #fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;    #或用$document_root,
    include fastcgi_params;
}
fastcgi快取定義:
fastcgi_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] 
[loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time]; path #快取位置為磁碟上的檔案系統路徑 max_size=size #磁碟path路徑中用於快取資料的快取空間上限 levels=levels: #快取目錄的層級數量,以及每一級的目錄數量,levels=ONE:TWO:THREE,示例:leves=1:2:2 keys_zone=name:size #設定快取名稱及k/v對映的記憶體空間的名稱及大小 inactive=time #快取有效時間,預設10分鐘,需要在指定時間滿足fastcgi_cache_min_uses 次數被視為活動快取 fastcgi快取呼叫: fastcgi_cache zone | off; #呼叫指定的快取空間來快取資料,可用位置:http, server, location fastcgi_cache_key string; #定義用作快取項的key的字串,示例:fastcgi_cache_key $request_uri; fastcgi_cache_methods GET | HEAD | POST ...; #為哪些請求方法使用快取 fastcgi_cache_min_uses number; #快取空間中的快取項在inactive定義的非活動時間內至少要被訪問到此處所指定的次數方可被認作活動項 fastcgi_keep_conn on | off; #收到後端伺服器響應後,fastcgi伺服器是否關閉連線,建議啟用長連線 fastcgi_cache_valid [code ...] time; #不同的響應碼各自的快取時長 fastcgi_hide_header field; #隱藏響應頭指定資訊 fastcgi_pass_header field; #返回響應頭指定資訊,預設不會將Status、X-Accel-...返回

 Nginx與php-fpm實現:

(1) 安裝php-fpm
[root@www ~]# yum install php-fpm php-mysql -y
[root@www ~]# systemctl start php-fpm
(2) 準備php測試頁
[root@www ~]# vim /usr/local/nginx/html/aaa.com/index.php
<?php
    phpinfo();
?>
(3) nginx配置轉發
[root@www ~]# vim /usr/local/nginx/conf/conf.d/aaa.conf
server {
    listen 80;
    server_name www.aaa.com;
    location / {
        root html/aaa.com;
        index index.html index.htm;
    }
    location ~ \.php$ {
        root html/aaa.com;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}
(3) 重啟nginx並使用瀏覽器測試
[root@www ~]# nginx -s reload

php相關配置優化:
[root@www ~]# grep "^[a-Z]" /etc/php-fpm.conf
include=/etc/php-fpm.d/*.conf
pid = /run/php-fpm/php-fpm.pid
error_log = /var/log/php-fpm/error.log
daemonize = yes        #是否後臺啟動

[root@www ~]# grep "^[a-Z]" /etc/php-fpm.d/www.conf 
listen = 127.0.0.1:9000                    #監聽地址及IP
listen.allowed_clients = 127.0.0.1        #允許客戶端從哪個源IP地址訪問,要允許所有則在行首加 ; 註釋即可
user = nginx                            #php-fpm啟動的使用者和組,會涉及到後期檔案的許可權問題
group = nginx
pm = dynamic                            #動態模式程序管理
pm.max_children = 500                    #靜態方式下開啟的php-fpm程序數量,在動態方式下他限定php-fpm的最大程序數
pm.start_servers = 100                    #動態模式下初始程序數,必須大於等於pm.min_spare_servers和小於等於pm.max_children的值
pm.min_spare_servers = 100                #最小空閒程序數
pm.max_spare_servers = 200                #最大空閒程序數
pm.max_requests = 500000                #程序累計請求回收值,會重啟
pm.status_path = /pm_status             #狀態訪問URL
ping.path = /ping                         #ping訪問動地址
ping.response = ping-pong                 #ping返回值
slowlog = /var/log/php-fpm/www-slow.log    #慢日誌路徑
php_admin_value[error_log] = /var/log/php-fpm/www-error.log        #錯誤日誌
php_admin_flag[log_errors] = on
php_value[session.save_handler] = files                            #phpsession儲存方式及路徑
php_value[session.save_path] = /var/lib/php/session                #當時使用file儲存session的檔案路徑

五、系統引數優化

 預設的Linux核心引數考慮的是最通用場景,不符合用於支援高併發訪問的Web伺服器的定義,根據業務特點來進行調整,當Nginx作為靜態web內容伺服器、反向代理或者提供壓縮伺服器的伺服器時,核心引數的調整都是不同的,此處針對最通用的、使Nginx支援更多併發請求的TCP網路引數做簡單的配置,修改/etc/sysctl.conf來更改核心引數。

fs.file-max = 1000000
#表示單個程序較大可以開啟的控制代碼數

net.ipv4.tcp_tw_reuse = 1
#引數設定為 1 ,表示允許將TIME_WAIT狀態的socket重新用於新的TCP連結,這對於伺服器來說意義重大,因為總有大量TIME_WAIT狀態的連結存在

net.ipv4.tcp_keepalive_time = 600
#當keepalive啟動時,TCP傳送keepalive訊息的頻度;預設是2小時,將其設定為10分鐘,可更快的清理無效連結

net.ipv4.tcp_fin_timeout = 30
#當伺服器主動關閉連結時,socket保持在FIN_WAIT_2狀態的較大時間

net.ipv4.tcp_max_tw_buckets = 5000
#表示作業系統允許TIME_WAIT套接字數量的較大值,如超過此值,TIME_WAIT套接字將立刻被清除並列印警告資訊,預設為8000,過多的TIME_WAIT套接字會使Web伺服器變慢

net.ipv4.ip_local_port_range = 1024 65000
#定義UDP和TCP連結的本地埠的取值範圍

net.ipv4.tcp_rmem = 10240 87380 12582912
#定義了TCP接受快取的最小值、預設值、較大值

net.ipv4.tcp_wmem = 10240 87380 12582912
#定義TCP傳送快取的最小值、預設值、較大值

net.core.netdev_max_backlog = 8096
#當網絡卡接收資料包的速度大於核心處理速度時,會有一個列隊儲存這些資料包。這個引數表示該列隊的較大值

net.core.rmem_default = 6291456
#表示核心套接字接受快取區預設大小

net.core.wmem_default = 6291456
#表示核心套接字傳送快取區預設大小

net.core.rmem_max = 12582912
#表示核心套接字接受快取區較大大小

net.core.wmem_max = 12582912
#表示核心套接字傳送快取區較大大小

注意:以上的四個引數,需要根據業務邏輯和實際的硬體成本來綜合考慮

net.ipv4.tcp_syncookies = 1
#與效能無關。用於解決TCP的SYN攻擊

net.ipv4.tcp_max_syn_backlog = 8192
#這個引數表示TCP三次握手建立階段接受SYN請求列隊的較大長度,預設1024,將其設定的大一些可使出現Nginx繁忙來不及accept新連線時,Linux不至於丟失客戶端發起的連結請求

net.ipv4.tcp_tw_recycle = 1
#這個引數用於設定啟用timewait快速回收

net.core.somaxconn=262114
#選項預設值是128,這個引數用於調節系統同時發起的TCP連線數,在高併發的請求中,預設的值可能會導致連結超時或者重傳,因此需要結合高併發請求數來調節此值。

net.ipv4.tcp_max_orphans=262114
#選項用於設定系統中最多有多少個TCP套接字不被關聯到任何一個使用者檔案控制代碼上。如果超過這個數字,孤立連結將立即被複位並輸出警告資訊。這個限制指示為了防止簡單的DOS攻擊,不用過分依靠這個限制甚至認為的減小這個值,更多的情況是增加這個值