Nginx深度優化

Nginx 以事件驅動(epoll)的方式編寫,所以有非常好的性能,同時也是一個非常高效的反 向代理、負載平衡。但是 Nginx 並不支持 cgi 方式運行,原因是可以減少因此帶來的一些程 序上的漏洞。所以必須使用 FastCGI 方式來執行 PHP 程序。 由於 Nginx 本身的一些優點,輕量,開源,易用,越來越多的公司使用 nginx 作爲自己公司 的 web 應用服務器,本文詳細介紹 nginx 源碼安裝的同時並對 nginx 進行優化配置。 可以通過nginx初步優化nginx反向代理來初步瞭解nginx

博文結構
編譯安裝前優化
nginx主配置優化
nginx配置防盜鏈
驗證上述優化

一.nginx編譯前優化

下載nginx軟件包

  • 安裝nginx及安裝 zlib-devel、pcre-devel 等依賴包
[root@localhost ~]# tar zxf nginx-1.14.0.tar.gz 
[root@localhost ~]# yum -y install pcre-devel openssl-devel
[root@localhost ~]# cd nginx-1.14.0/
[root@localhost nginx-1.14.0]# groupadd www
[root@localhost nginx-1.14.0]# useradd -g www www -s /sbin/nologin 
[root@localhost nginx-1.14.0]# ./configure --prefix=/usr/local/nginx --user=nginx \
 --group=nginx --with-http_dav_module --with-http_stub_status_module \
 --with-http_addition_module --with-http_sub_module --with-http_flv_module \
 --with-http_mp4_module --with-pcre --with-http_ssl_module \
 --with-http_gzip_static_module \
 --user=www --group=www && make && make install
[root@localhost nginx-1.14.0]# ln -s /usr/local/nginx/sbin/nginx  /usr/local/sbin/
[root@localhost nginx-1.14.0]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost nginx-1.14.0]# nginx 
  • 配置項註釋:
--with-http_dav_module:增加 PUT,DELETE,MKCOL:創建集合,COPY 和 MOVE 方法;
--with-http_stub_status_module:獲取 Nginx 的狀態統計信息;
--with-http_addition_module:作爲一個輸出過濾器,支持不完全緩衝,分部分相應請求;
--with-http_sub_module:允許一些其他文本替換 Nginx 相應中的一些文本;
--with-http_flv_module:提供支持 flv 視頻文件支持;
--with-http_mp4_module:提供支持 mp4 視頻文件支持,提供僞流媒體服務端支持;
--with-http_ssl_module:啓用 ngx_http_ssl_module;
  • nginx常用選項
-v:顯示版本信息;
-V:顯示版本信息及配置選項參數;
-t:測試配置文件是否有語法錯誤;
-T:測試配置文件並將配置文件顯示出來;
-q:在配置期間抑制非錯誤信息;
-s (stop, quit, reopen, reload ):向主進程發送信號:停止、退出、重新打開、重新加載;
-c:設置配置文件;
-g:從配置文件中設置全局指令;

二.nginx主配置優化

Nginx是master/worker結構:一個master進程,生成一個或多個worker進程

Nginx深度優化

  • Nginx 運行工作進程個數

[root@localhost /]# cat /proc/cpuinfo | grep process | wc -l
\可以看到當前cpu爲1
[root@localhost /]# vim /usr/local/nginx/conf/nginx.conf \在上面添加如下
worker_processes 2; //工作進程數,建議是CPU數或者是CPU個數的兩倍,最大可以開啓8個
[root@localhost ~]# nginx -s reload
[root@localhost ~]# ps -ef | grep nginx | grep worker
www 22142 21831 0 13:56 ? 00:00:00 nginx: worker process
www 22143 21831 0 13:56 ? 00:00:00 nginx: worker process
\可以看到剛纔更改已經生效

  • Nginx運行CPU親和力
[root@nginx ~]# vim /usr/local/nginx1.14/conf/nginx.conf 
worker_processes  2; 
worker_cpu_affinity 01 10;     //運行CPU親和力
worker_rlimit_nofile 65535;             //最多打開的文件個數
[root@localhost ~]# ulimit -n   \\看到系統默認限制打文件的個數是1024
1024
[root@localhost ~]# vim /etc/security/limits.conf   \\在最下面原有的內容添加
#<domain>      <type>  <item>         <value>
*               soft      nofile                      65535                 //添加軟限制打開文件的個數
*               hard     nofile                     65535                 //添加新限制打開文件的個數
*               soft      noproc                  65535                 //添加軟連接可以打開的進程個數
*               hard     noproc                 65535                //添加硬限制可以打開的進程個數
[root@localhost /]# su -                         \\切換一下用戶可以生效
上一次登錄:四 1月  2 13:24:58 CST 2020從 192.168.148.1pts/1 上
[root@localhost ~]# ulimit -n
65535
  • Nginx 事件處理模型

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf \在events中添加
use epoll;
worker_connections 65535;
multi_accept on;
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

  • 註釋

    use epol :採用epoll事件模型,處理效率高 
    work_connections :是單個 worker 進程允許客戶端最大連接數,這個數值一般根據服務器性 能和內存來制定,實際最大值就是 worker 進程數乘以 work_connections 實際我們填入一個 65535,足夠了,這些都算併發值,一個網站的並發達到這麼大的數量,也算一個大站了
    multi_accept :告訴 nginx 收到一個新連接通知後接受儘可能多的連接
  • 開啓高效傳輸模式
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf  \\在http中添加,如果已經有可以註釋掉
http {
    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;
    tcp_nopush     on;
  • 註釋
nclude mime.types:媒體類型, include 只是一個在當前文件中包含另一個文件內容的指令 ;
default_type application/octet-stream:默認媒體類型足夠;
sendfile on:開啓高效文件傳輸模式,sendfile 指令指定 nginx 是否調用 sendfile 函數來 輸出文件,對於普通應用設爲 on,如果用來進行下載等應用磁盤 IO 重負載應用,可設置爲 off,以平衡磁盤與網絡 I/O 處理速度,降低系統的負載。
注意:如果圖片顯示不正常把這個改成 off。
tcp_nopush on; 必須在 sendfile 開啓模式纔有效,防止網路阻塞,積極的減少網絡報文 段的數量(告訴 nginx 在一個數據包裏發送所有頭文件,而不一個接一個的發送。
  • 連接超時時
    主要目的是保護服務器資源,CPU,內存,控制連接數,因爲建立連接也是需要消耗資源
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf  \\在http中添加,keepalive已經有先註釋掉,然後添加

                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;
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
  • 註釋
keepalived_timeout:客戶端連接保持會話超時時間,超過這個時間,服務器斷開這個鏈接;
tcp_nodelay;也是防止網絡阻塞,不過要包涵在 keepalived 參數纔有效;
client_header_buffer_size 4k:客戶端請求頭部的緩衝區大小,這個可以根據你的系統分頁大小來設置,一般一個請求頭的大小不會超過 1k,不過由於一般系統分頁都要大於 1k,所以這裏設置爲分頁大小。分頁大小可以用命令 getconf PAGESIZE 取得;
open_file_cache max=102400 inactive=20s:這個將爲打開文件指定緩存,默認是沒有啓用的,max 指定緩存數量,建議和打開文件數一致,inactive 是指經過多長時間文件沒被請求後刪除緩存;
open_file_cache_valid 30s:這個是指多長時間檢查一次緩存的有效信息;
open_file_cache_min_uses 1:open_file_cache 指令中的 inactive 參數時間內文件的最少使用次數,如果超過這個數字,文件描述符一直是在緩存中打開的,如上例,如果有一個文件在 inactive 時間內一次沒被使用,它將被移除;
client_header_timeout:設置請求頭的超時時間。我們也可以把這個設置低些,如果超過這個時間沒有發送任何數據,nginx 將返回 request time out 的錯誤;
client_body_timeout:設置請求體的超時時間。我們也可以把這個設置低些,超過這個時間沒有發送任何數據,和上面一樣的錯誤提示;
reset_timeout_connection 告訴 nginx 關閉不響應的客戶端連接。這將會釋放那個客戶端所佔有的內存空間;
send_timeout 響應客戶端超時時間,這個超時時間僅限於兩個活動之間的時間,如果超過這個時間,客戶端沒有任何活動,nginx 關閉連接;
server_tokens 並不會讓 nginx 執行的速度更快,但它可以關閉在錯誤頁面中的 nginx 版本數字,這樣對於安全性是有好處的;
client_max_body_size 上傳文件大小限制;
  • fastcgi調優
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf  \\接着上面http中添加
        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;
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
  • 註釋
Cache: 寫入緩存區;
Buffer: 讀取緩存區;
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 的應答請求,如果 一個 php 腳本所產生的頁面大小爲 256KB,那麼會分配 4 個 64KB 的緩衝區來緩存,如果頁 面大小大於 256KB,那麼大於 256KB 的部分會緩存到fastcgi_temp_path 指定的路徑中,但是 這並不是好方法,因爲內存中的數據處理速度要快於磁盤。一般這個值應該爲站點中 php 腳本所產生的頁面大小的中間值,如果站點大部分腳本所產生的頁面大小爲 256KB,那麼可 以把這個值設置爲“8 32K”、“4 64k”等;
fastcgi_busy_buffers_size 128k:建議設置爲 fastcgi_buffers 的兩倍,繁忙時候的 buffer;
fastcgi_temp_file_write_size 128k:在寫入 fastcgi_temp_path 時將用多大的數據塊,默認值是 fastcgi_buffers 的兩倍,該數值設置小時若負載上來時可能報 502 Bad Gateway;
fastcgi_temp_path /usr/local/nginx1.10/nginx_tmp:緩存臨時目錄;
fastcgi_intercept_errors on:這個指令指定是否傳遞 4xx 和 5xx 錯誤信息到客戶端,或者允許 nginx 使用 error_page 處理錯誤信息;
fastcgi_cache_path /usr/local/nginx1.10/fastcgi_cache levels=1:2
keys_zone=cache_fastcgi:128m inactive=1d max_size=10g:fastcgi_cache 緩存目錄,可以設置目錄層級,比如 1:2 會生成 16*256 個子目錄,cache_fastcgi 是這個緩存空間的名字,cache 是用多少內存(這樣熱門的 內容 nginx 直接放內存,提高訪問速度),inactive 表示默認失效時間,如果緩存數據在失效 時間內沒有被訪問,將被刪除,max_size 表示最多用多少硬盤空間;
fastcgi_cache cache_fastcgi:表示開啓 FastCGI 緩存併爲其指定一個名稱。開啓緩存非常有 用,可以有效降低 CPU 的負載,並且防止 502 的錯誤放生。cache_fastcgi 爲 proxy_cache_path 指令創建的緩存區名稱;
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 1:該指令用於設置經過多少次請求的相同 URL 將被緩存;
fastcgi_cache_key http://$host$request_uri :該指令用來設置web緩存的Key值,nginx根據Key 值 md5 哈希存儲.一般根據$host(域名)、$request_uri(請求的路徑)等變量組合成 proxy_cache_key;
fastcgi_pass:指定 FastCGI 服務器監聽端口與地址,可以是本機或者其它;
  • 總結上述:

nginx 的緩存功能有:proxy_cache / fastcgi_cache proxy_cache 的作用是緩存後端服務器的內容,可能是任何內容,包括靜態的和動態。 fastcgi_cache 的作用是緩存 fastcgi 生成的內容,很多情況是 php 生成的動態的內容。 proxy_cache 緩存減少了 nginx 與後端通信的次數,節省了傳輸時間和後端寬帶。 fastcgi_cache緩存減少了nginx與php的通信的次數,更減輕了php和數據庫(mysql)的壓力。

  • gzip 調優
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf  \\在http中有個被註釋掉的gzip,在它下面添加

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;
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
  • 註釋:
gzip on:開啓壓縮功能;
gzip_min_length 1k:設置允許壓縮的頁面最小字節數,頁面字節數從 header 頭的Content-Length 中獲取,默認值是 0,不管頁面多大都進行壓縮,建議設置成大於 1K,如果小與 1K 可能會越壓越大;
gzip_buffers 4 32k:壓縮緩衝區大小,表示申請4個單位爲32K的內存作爲壓縮結果流緩存,默認值是申請與原始數據大小相同的內存空間來存儲 gzip 壓縮結果;
gzip_http_version 1.1:壓縮版本,用於設置識別 HTTP 協議版本,默認是 1.1,目前大部分瀏覽器已經支持 GZIP 解壓,使用默認即可;
gzip_comp_level 6:壓縮比例,用來指定 GZIP 壓縮比,1 壓縮比最小,處理速度最快,9 壓縮比最大,傳輸速度快,但是處理慢,也比較消耗 CPU 資源;
gzip_types text/css text/xml application/javascript:用來指定壓縮的類型,‘text/html’類型總是會被壓縮。
默認值: gzip_types text/html (默認不對 js/css 文件進行壓縮)
#壓縮類型,匹配 MIME 類型進行壓縮
#不能用通配符 text/*
#(無論是否指定)text/html 默認已經壓縮
#設置哪壓縮種文本文件可參考 conf/mime.types
gzip_vary on:vary header 支持,該選項可以讓前端的緩存服務器緩存經過 GZIP 壓縮的頁面,例如用 Squid 緩存經過 nginx 壓縮的數據
  • expires 緩存調優
    緩存,主要針對於圖片,css,js 等元素更改機會比較少的情況下使用,特別是圖片,佔用帶寬大,我們完全可以設置圖片在瀏覽器本地緩存 365d,css,js,html 可以緩存個 10 來天,這樣用戶第一次打開加載慢一點,第二次,就非常快了!緩存的時候,我們需要將需要緩存的拓展名列出來。
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf    \\在server字段中添加

location ~* \.(ico|jpe?g|gif|png|bmp|swf|flv)$ {
 expires 30d;                             //緩存時間爲30天
 #log_not_found off;                 //是否在 error_log 中記錄不存在的錯誤
 access_log off;                            //不記錄日誌
}
location ~* \.(js|css)$ {
 expires 7d;              
 log_not_found off;    
 access_log off;              
}
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

expire 功能優點

expires 可以降低網站購買的帶寬,節約成本,同時提升用戶訪問體驗;
減輕服務的壓力,節約服務器成本,是 web 服務非常重要的功能。 expire 功能
缺點:被緩存的頁面或數據更新了,用戶看到的可能還是舊的內容,反而影響用戶體驗。解決辦法: 第一個縮短緩存時間,例如:1 天,但不徹底,除非更新頻率大於 1 天;第二個對緩存的對象改名。
  • 網站不希望被緩存的內容
1)網站流量統計工具;
2)更新頻繁的文件(google 的 logo);
  • 防盜鏈

下面的方法是直接給予 404 的錯誤提示或者跳轉到指定提示頁面。

[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf    \\在server字段中添加

location ~* ^.+\.(jpg|gif|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
            valid_referers none blocked 192.168.148.131;    #該字段是指定允許跳轉訪問的域名,也可以是本機ip
            if ($invalid_referer) {
            #return 302 http://www.test.com/img/nolink.png;   #該註釋的配置項表示可以將其重定向到指定文件
            return 404;          #這裏是直接返回給客戶端狀態碼404
            break;
            }
            access_log off;         #關閉訪問日誌
          }
        location / {            #防盜鏈配置必須寫在所有location字段之前
            root   html;
            index  index.html index.htm;
        }
[root@localhost ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
  • 下面是剛纔修改過的全部內容
#user  nobody;
worker_processes  4;
worker_cpu_affinity 0001 0010 0100 1000;
worker_rlimit_nofile 65535;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    use epoll;
    worker_connections  65535;
    multi_accept on;
}

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;
    tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;
    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;

    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/nginx1.10/nginx_tmp;
    fastcgi_intercept_errors on;
    fastcgi_cache_path /usr/local/nginx1.10/fastcgi_cache levels=1:2 keys_zone=cache_fastcgi:128m inactive=1d max_size=10g;
    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;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
        location ~* ^.+\.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
            valid_referers none blocked 192.168.148.131;
            if ($invalid_referer) {
            return 302 http:////www.benet.com/img/nolink.jpg;
            #return 404;
            break;
            }
            access_log off;
          }
        location / {
            root   html;
            index  index.html index.htm;
        }
        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;
        }
[root@localhost ~]# nginx -s reload    \\重載nginx
  • 內核參數優化
[root@localhost ~]# vim /etc/sysctl.conf         \\在末尾添加
fs.file-max = 999999
net.ipv4.ip_forward = 0
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
kernel.sysrq = 0
kernel.core_uses_pid = 1
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.tcp_sack = 1
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_rmem = 10240 87380 12582912
net.ipv4.tcp_wmem = 10240 87380 12582912
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.netdev_max_backlog = 262144
net.core.somaxconn = 40960
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_fin_timeout = 1
net.ipv4.tcp_keepalive_time = 30
net.ipv4.ip_local_port_range = 1024 65000
[root@localhost ~]# sysctl -p   \\刷新,使內核修改生效,正常的話,會返回所有配置項
  • 註釋
fs.file-max = 999999:這個參數表示進程(比如一個 worker 進程)可以同時打開的最大句柄數,這個參數直線限制最大併發連接數,需根據實際情況配置。
net.ipv4.tcp_max_tw_buckets = 6000 :這個參數表示操作系統允許 TIME_WAIT 套接字數量的最大值,如果超過這個數字,TIME_WAIT 套接字將立刻被清除並打印警告信息。該參數默認爲 180000,過多的 TIME_WAIT 套接字會使 Web 服務器變慢。
注:主動關閉連接的服務端會產生 TIME_WAIT 狀態的連接
net.ipv4.ip_local_port_range = 1024 65000 :允許系統打開的端口範圍。
net.ipv4.tcp_tw_recycle = 1:啓用 timewait 快速回收。
net.ipv4.tcp_tw_reuse = 1:開啓重用。允許將 TIME-WAIT sockets 重新用於新的 TCP 連接。這對於服務器來說很有意義,因爲服務器上總會有大量 TIME-WAIT 狀態的連接。
net.ipv4.tcp_keepalive_time = 30:這個參數表示當 keepalive 啓用時,TCP 發送 keepalive 消息的頻度。默認是 2 小時,若將其設置的小一些,可以更快地清理無效的連接。
net.ipv4.tcp_syncookies = 1 :開啓 SYN Cookies,當出現 SYN 等待隊列溢出時,啓用 cookies 來處理。
net.core.somaxconn = 40960 :web 應用中 listen 函數的 backlog 默認會給我們內核參數的
net.core.somaxconn: 限制到 128,而 nginx 定義的 NGX_LISTEN_BACKLOG 默認爲 511,所以有必要調整這個值。
注:對於一個 TCP 連接,Server 與 Client 需要通過三次握手來建立網絡連接.當三次握手成功後,我們可以看到端口的狀態由 LISTEN 轉變爲 ESTABLISHED,接着這條鏈路上就可以開始傳送數據了.每一個處於監聽(Listen)狀態的端口,都有自己的監聽隊列.監聽隊列的長度與如
somaxconn 參數和使用該端口的程序中 listen()函數有關;
somaxconn參數:定義了系統中每一個端口最大的監聽隊列的長度,這是個全局的參數,默認值爲 128,對於一個經常處理新連接的高負載 web 服務環境來說,默認的 128 太小了。大多數環境這個值建議增加到 1024 或者更多。大的偵聽隊列對防止拒絕服務 DoS ***也會有
所幫助。
net.core.netdev_max_backlog = 262144 :每個網絡接口接收數據包的速率比內核處理這些包的速率快時,允許送到隊列的數據包的最大數目。
net.ipv4.tcp_max_syn_backlog = 262144 :這個參數標示 TCP 三次握手建立階段接受 SYN 請求隊列的最大長度,默認爲 1024,將其設置得大一些可以使出現 Nginx 繁忙來不及 accept 新連接的情況時,Linux 不至於丟失客戶端發起的連接請求。
net.ipv4.tcp_rmem = 10240 87380 12582912:這個參數定義了 TCP 接受緩存(用於 TCP 接受滑動窗口)的最小值、默認值、最大值。
net.ipv4.tcp_wmem = 10240 87380 12582912:這個參數定義了 TCP 發送緩存(用於 TCP 發送滑動窗口)的最小值、默認值、最大值。
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 “gong擊” 。

三.驗證上述優化

  • 驗證防盜鏈
    開一臺httpd服務器,寫一個測試文件
ip爲192.168.148.132
nginx ip爲192.168.148.131
  • nginx服務器操作如下:

先下載倆張圖片

[root@localhost ~]# cd /usr/local/nginx/html/
[root@localhost html]# mkdir xws
[root@localhost html]# cd xws
[root@localhost xws]# mv /root/u=2242212773\,2792770847\&fm\=26\&gp\=0.jpg  a.jpg
[root@localhost xws]# mv /root/u=1806047429\,2669047046\&fm\=26\&gp\=0.jpg  error.jpg
[root@localhost xws]# ls
a.jpg  error.jpg
  • http服務器操作如下:
[root@localhost ~]# yum -y install httpd
[root@localhost ~]# systemctl start httpd
[root@localhost ~]# vim /var/www/html/index.html
<a href="http://192.168.148.131/a.jpg">lianjie</a>

訪問效果如下:

Nginx深度優化

Nginx深度優化

因爲上面配置文件中設置的是訪問結果是404,所以會看到404
如果把那個404用#註釋掉,把那個302打開,訪問就會出現鏈接圖片,狀態碼爲302
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章