nginx配置文件優化(詳細)

nginx優化項

  • 隱藏nginx版本
  • nginx 配置項優化
  • 開啓高效傳輸模式
  • fastcgi 調優
  • gzip 調優
  • expires 緩存調優
  • 內核參數優化
  • 系統連接數的優化

準備nginx測試環境

  1. nginx安裝略

  2. 準備測試文件

      vim /usr/local/nginx/conf/nginx.conf
      echo 'Hello world ' > /usr/local/nginx/html/index.html
    
  3. 啓動nginx服務

    systemctl start nginx
    [root@localhost ~]# curl -I http://172.16.46.114
    HTTP/1.1 200 OK
    Server: nginx/1.12.2   #這裏顯示版本號
    Date: Sat, 04 Jul 2020 05:20:43 GMT
    Content-Type: text/html
    Content-Length: 13
    Last-Modified: Sat, 04 Jul 2020 03:57:39 GMT
    Connection: keep-alive
    ETag: "5efffe33-d"
    Accept-Ranges: bytes
    
    [root@localhost ~]# 
    [root@localhost ~]# 
    [root@localhost ~]# curl  http://172.16.46.114
    Hello world 
    
    

隱藏nginx版本的2種方法

  1. 通過修改nginx配置文件的方法

    在HTTP字段添加下
    在這裏插入圖片描述

再次查看請求頭

[root@localhost ~]# systemctl restart nginx
[root@localhost ~]# curl -I http://172.16.46.114
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 04 Jul 2020 05:22:34 GMT
Content-Type: text/html
Content-Length: 13
Last-Modified: Sat, 04 Jul 2020 03:57:39 GMT
Connection: keep-alive
ETag: "5efffe33-d"
Accept-Ranges: bytes

在這裏插入圖片描述

  1. 重新編譯法

    修改源碼包文件src/core/nginx.h

    [root@localhost src]# cd nginx-1.12.2/
    [root@localhost nginx-1.12.2]# vim src/core/nginx.h 
    [root@localhost nginx-1.12.2]# vi src/http/ngx_http_header_filter_module.c #徹底隱藏HTTP 頭信息中的 connection 字段
    [root@localhost nginx-1.12.2]# vi src/http/ngx_http_special_response.c #隱藏錯誤頁面版本顯示
    [root@localhost nginx-1.12.2]# make && make install
    

src/core/nginx.h 修改如下:
在這裏插入圖片描述

[root@www nginx-1.12.2]# vi src/http/ngx_http_header_filter_module.c
修改前:
static char ngx_http_server_string[] = "Server: nginx" CRLF; //第 49 行
修改後:
static char ngx_http_server_string[] = "Server: IIS" CRLF;
[root@www nginx-1.12.2]# vi src/http/ngx_http_special_response.c
修改前
static u_char ngx_http_error_tail[] = //第 29 行
"<hr><center>nginx</center>" CRLF
"</body>" CRLF
"</html>" CRLF
;
修改後
static u_char ngx_http_error_tail[] =
"<hr><center>IIS</center>" CRLF
"</body>" CRLF
"</html>" CRLF
;
[root@localhost ~]# nginx -v
nginx version: IIS/8.8.8.8

nginx配置項優化

nginx運行CPU親和力

worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000

8核如下

worker_processes 8;

worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000

10000000;

2核如下:
worker_processes 2;
worker_cpu_affinity 0101 1010;

nginx最多可以打開的文件數

一個工作進程(worker process)建立一個連接後,進程將會打開一個文件副本,所以這個數(worker_connections)的大小還和操作系統設定的進程最大可打開的文件副本數有關。

worker_rlimit_nofile 65535;

#這個指令是指當一個 nginx 進程打開的最多文件描述符數目,理論值應該是最多打開文件數
(ulimit -n)與 nginx 進程數相除,但是 nginx 分配請求並不是那麼均勻,所以最好與 ulimit -n
的值保持一致

#文件資源限制的配置可以在/etc/security/limits.conf 設置,針對 root/user 等各個用戶或者*
代表所有用戶來設置。
*		soft 	nofile 65535
*		hard 	nofile 65535
*		soft    noproc 65535
*       hard    noproc 65535

nginx事件處理模型

events {
use epoll;
worker_connections 65535;
multi_accept on;
}
#nginx 採用 epoll 事件模型,處理效率高
#work_connections 是單個 worker 進程允許客戶端最大連接數,這個數值一般根據服務器性
能和內存來制定,實際最大值就是 `worker 進程數乘以 work_connections`
實際我們填入一個 65535,足夠了,這些都算併發值,一個網站的併發達到這麼大的數量,
也算一個大站了!
`multi_accept 告訴 nginx 收到一個新連接通知後接受盡可能多的連接`

開啓高效傳輸模式

http {
include mime.types;
default_type application/octet-stream;
……
sendfile on;
tcp_nopush on;
……

註釋:

# Include mime.types; //媒體類型, include 只是一個在當前文件中包含另一個文件內容的指令
# default_type application/octet-stream; //默認媒體類型足夠
# sendfile on; //開啓高效文件傳輸模式,
# tcp_nopush on; 必須在 sendfile 開啓模式纔有效,防止網路阻塞,積極的減少網絡報文段的數量

連接超時時間

keepalive_timeout 60;
tcp_nodelay on;
client_header_buffer_size 4k;
open_file_cache max=102400 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 1;
client_header_timeout 15;
client_body_timeout 15;
reset_timedout_connection on;
send_timeout 15;
server_tokens off;
client_max_body_size 10m;
# keepalived_timeout; 客戶端連接保持會話超時時間,超過這個時間,服務器斷開這個鏈接
# tcp_nodelay;也是防止網絡阻塞,不過要包涵在 keepalived 參數纔有效
# client_header_buffer_size 4k; 客戶端請求頭部的緩衝區大小
# open_file_cache max=102400 inactive=20s;這個將爲打開文件指定緩存,默認是沒有啓用的
# open_file_cache_valid 30s;這個是指多長時間檢查一次緩存的有效信息。
# open_file_cache_min_uses 1;
# open_file_cache 指令中的 inactive 參數時間內文件的最少使用次數,如果超過這個數字,文件描述符一直是在緩存中打開的
# client_header_timeout 設置請求頭的超時時間
# client_body_timeout 設置請求體的超時時間
# reset_timeout_connection 告訴 nginx 關閉不響應的客戶端連接。
# send_timeout 響應客戶端超時時間
# server_tokens 並不會讓 nginx 執行的速度更快,但它可以關閉在錯誤頁面中的 nginx 版本數字,這樣對於安全性是有好處的。
# client_max_body_size; 上傳文件大小限制

fastcgi與proxy 緩存調優

nginx 的 web 緩存功能的主要是由 proxy_cachefastcgi_cache 指令集和關指令收集完成。

proxy_cache 指令負責反向代理緩存後端服務器的靜態內容

fastcgi_cache 主要用來處理FastCGI 動態進程緩存

 client_max_body_size 10m;
 client_body_buffer_size 128k;
 proxy_connect_timeout 75;
 proxy_send_timeout 75;
 proxy_read_timeout 75;
 proxy_buffer_size 4k;
 proxy_buffers 4 32k;
 proxy_busy_buffers_size 64k;
 proxy_temp_file_write_size 64k;
 proxy_buffering on;
 proxy_temp_path /usr/local/nginx/proxy_temp;
 proxy_cache_path /usr/local/nginx/proxy_cache levels=1:2 keys_zone=my-cache:100m 
 max_size=1000m inactive=600m max_size=2g;

nginx做反向代理轉發優化

代理參數

proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;

proxy_buffering on;
proxy_buffer_size 32k;
proxy_buffers 4 128k;

如果nginx後面接的是動態的網站,需要fastcgi接口轉發請求到(PHP)

緩存調優如下:

fastcgi_connect_timeout 600;
fastcgi_send_timeout 600;
fastcgi_read_timeout 600;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
fastcgi_temp_path /usr/local/nginx/nginx_tmp;
fastcgi_intercept_errors on;
fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=cache_fastcgi:128m 
inactive=1d max_size=10g;

轉發調優如下:

location ~ \.php$ {
                root /wordpress; 
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_index index.php; 
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;  
                fastcgi_cache cache_fastcgi;
			    fastcgi_cache_valid 200 302 1h;
 				fastcgi_cache_valid 301 1d;
				fastcgi_cache_valid any 1m;
 				fastcgi_cache_min_uses 1;
 				fastcgi_cache_key http://$host$request_uri;
                include fastcgi_params; #引用fastcgi_params目錄
        }

註釋:

fastcgi_connect_timeout 600; #指定連接到後端 FastCGI 的超時時間。
fastcgi_send_timeout 600; #向 FastCGI 傳送請求的超時時間。
fastcgi_read_timeout 600; #指定接收 FastCGI 應答的超時時間。
fastcgi_buffer_size 64k; #指定讀取 FastCGI 應答第一部分需要用多大的緩衝區,默認的緩衝區大小爲 fastcgi_buffers 指令中的每塊大小,可以將這個值設置更小。
fastcgi_buffers 4 64k; #指定本地需要用多少和多大的緩衝區來緩衝 FastCGI 的應答請求
fastcgi_busy_buffers_size 128k; #建議設置爲 fastcgi_buffers 的兩倍,繁忙時候的 buffer
fastcgi_temp_file_write_size 128k; #在寫入 fastcgi_temp_path 時將用多大的數據塊,默認值是 fastcgi_buffers 的兩倍
fastcgi_temp_path #緩存臨時目錄
fastcgi_intercept_errors on;# 這個指令指定是否傳遞 4xx 和 5xx 錯誤信息到客戶端,或者允許nginx 使用 error_page 處理錯誤信息
fastcgi_cache_path /usr/local/nginx/fastcgi_cache levels=1:2 keys_zone=cache_fastcgi:128m 
inactive=1d max_size=10g; # fastcgi_cache 緩存目錄
fastcgi_cache cache_fastcgi; #表示開啓 FastCGI 緩存併爲其指定一個名稱.inactive 表示默認
失效時間,如果緩存數據在失效時間內沒有被訪問,將被刪除,max_size 表示最多用多少硬盤空間
fastcgi_pass #指定 FastCGI 服務器監聽端口與地址
fastcgi_cache_valid 200 302 1h; #用來指定應答代碼的緩存時間,實例中的值表示將 200 和302 應答緩存一小時,要和 fastcgi_cache 配合使用
fastcgi_cache_valid 301 1d; #將 301 應答緩存一天
fastcgi_cache_valid any 1m; #將其他應答緩存爲 1 分鐘
fastcgi_cache_min_uses 3; #該指令用於設置經過多少次請求的相同 URL 將被緩存
fastcgi_cache_key http://$host$request_uri; #該指令用來設置web緩存的Key值,nginx根據Key
值 md5 哈希存 儲 .一 般根 據$host( 域名 )$request_uri(請 求的路 徑 ) 等變 量組 合成
proxy_cache_key

gzip 調優

使用 gzip 壓縮功能,可能爲我們節約帶寬,加快傳輸速度,有更好的體驗

同時也要注意,我們使用 gzip 的功能是需要消耗 CPU 的!

Nginx 啓用壓縮功能需要你來 ngx_http_gzip_module 模塊,一般我們需要壓縮的內容有:文本,js,html,css,對於圖片,視頻,flash 什麼的不壓縮;

gzip on;
gzip_min_length 2k;
gzip_buffers 4 32k;
gzip_http_version 1.1;
gzip_comp_level 6;
gzip_types text/plain text/css text/javascript application/json application/javascript 
application/x-javascript application/xml;
gzip_vary on;
gzip_proxied any;
gzip on; #開啓壓縮功能
gzip_min_length 1k; #設置允許壓縮的頁面最小字節數
gzip_buffers 4 32k; #壓縮緩衝區大小
gzip_http_version 1.1; #壓縮版本
gzip_comp_level 6; #壓縮比例,1 壓縮比最小,處理速度最快,9 壓縮比最大,傳輸速度快,但是處理慢,也比較消耗 CPU 資源;6比較中性
gzip_types text/css text/xml application/javascript; #用來指定壓縮的類型
gzip_vary on; #vary header 支持

expires 緩存調優

緩存,主要針對於圖片,css,js 等元素更改機會比較少的情況下使用,特別是圖片,佔用
帶寬大,我們完全可以設置圖片在瀏覽器本地緩存 30d,css,js,html 可以緩存個 10 來天,
這樣用戶第一次打開加載慢一點,第二次,就非常快了!緩存的時候,我們需要將需要緩存
的拓展名列出來, Expires 緩存配置在 server 字段裏面
location ~* \.(ico|jpe?g|gif|png|bmp|swf|flv)$ {
 expires 30d;
 log_not_found off;
 access_log off;
}
location ~* \.(js|css)$ {
 expires 7d;
 log_not_found off;
 access_log off;
}

log_not_found off;是否在 error_log 中記錄不存在的錯誤,默認是

nginx整體配置優化

在這裏插入圖片描述

在這裏插入圖片描述

在這裏插入圖片描述
在這裏插入圖片描述
關於系統連接數的優化

linux 默認值 open files 爲 1024

修改open files 最大連接數

如下圖:

在這裏插入圖片描述

編輯/etc/security/limits.conf

*       soft    nifile 65535
*       hard    nifile 65535
*       soft    noproc 65535
*       hard    noproc 65535

ulimit -n 65535 / reboot 保證本次會話生效

驗證生效

[root@localhost ~]# ps -aux | grep nginx
root       1006  0.0  0.0 177032  1288 ?        Ss   08:31   0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx      1009  0.3  1.5 206252 28804 ?        S    08:31   0:00 nginx: worker process
nginx      1010  0.2  1.5 206252 28804 ?        S    08:31   0:00 nginx: worker process
nginx      1011  0.0  0.0 179272  1776 ?        S    08:31   0:00 nginx: cache manager process
root       3365  0.0  0.0 112656   960 pts/0    S+   08:33   0:00 grep --color=auto nginx
[root@localhost ~]# cat /proc/1009/limits 
Limit                     Soft Limit           Hard Limit           Units     
Max cpu time              unlimited            unlimited            seconds   
Max file size             unlimited            unlimited            bytes     
Max data size             unlimited            unlimited            bytes     
Max stack size            8388608              unlimited            bytes     
Max core file size        0                    unlimited            bytes     
Max resident set          unlimited            unlimited            bytes     
Max processes             7179                 7179                 processes 
Max open files            65535                65535                files     
Max locked memory         65536                65536                bytes     
Max address space         unlimited            unlimited            bytes     
Max file locks            unlimited            unlimited            locks     
Max pending signals       7179                 7179                 signals   
Max msgqueue size         819200               819200               bytes     
Max nice priority         0                    0                    
Max realtime priority     0                    0                    
Max realtime timeout      unlimited            unlimited            us        

可見,openfile已經更改

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章