Nginx 優化與防盜鏈實踐教程

51cto發表於2017-03-25

Nginx是俄羅斯人編寫的十分輕量級的HTTP伺服器,Nginx,它的發音為“engine X”,是一個高效能的HTTP和反向代理伺服器,同時也是一個IMAP/POP3/SMTP 代理伺服器.Nginx是由俄羅斯人Igor Sysoev為俄羅斯訪問量第二的Rambler.ru站點開發.

Nginx以事件驅動(epoll)的方式編寫,所以有非常好的效能,同時也是一個非常高效的反向代理、負載平衡。但是Nginx並不支援cgi方式執行,原因是可以減少因此帶來的一些程式上的漏洞。所以必須使用FastCGI方式來執行PHP程式。

由於Nginx本身的一些優點,輕量,開源,易用,越來越多的公司使用nginx作為自己公司的web應用伺服器,本文詳細介紹nginx原始碼安裝的同時並對nginx進行優化配置。

一、Nginx的優化

1、編譯安裝前優化

編譯前的優化主要是用來修改程式名等等,目的更改原始碼隱藏軟體名稱和版本號

安裝zlib-devel、pcre-devel等依賴包

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

下載nginx的原始碼包:http://nginx.org/download

解壓原始碼包:

[root@localhost ~]# tar zxf nginx-1.10.2.tar.gz 
[root@localhost ~]# cd nginx-1.10.2/

隱藏軟體名稱和版本號

[root@localhost nginx-1.10.2]# vi src/core/nginx.h

隱藏軟體名稱和版本號

#defineNGINX_VERSION      "1.10.2"    //第13行 

//此行修改的是你想修改的軟體名稱 

#defineNGINX_VER          "nginx/" NGINX_VERSION  //第14行

修改上面的資訊,即可更改nginx顯示版本。例如:

#define NGINX_VERSION      "7.0" 
#defineNGINX_VER          "IIS/" NGINX_VERSION

修改HTTP頭資訊中的connection欄位,防止回顯具體版本號

擴充:通用http頭,通用頭包含請求和響應訊息都支援的頭,通用頭包含Cache-Control、 Connection、Date、Pragma、Transfer-Encoding、Upgrade、Via。對通用頭的擴充套件要求通訊雙方都支援此擴充套件,如果存在不支援的通用頭,一般將會作為實體頭處理。那麼也就是說有部分裝置,或者是軟體,能獲取到connection,部分不能,要隱藏就要徹底!

[root@localhost nginx-1.10.2]# vi src/http/ngx_http_header_filter_module.c

修改前:

static char ngx_http_server_string[] ="Server: nginx" CRLF;  //第49行

修改後:

staticchar ngx_http_server_string[] = "Server: IIS"CRLF

定義了http錯誤碼的返回

有時候我們頁面程式出現錯誤,Nginx會代我們返回相應的錯誤程式碼,回顯的時候,會帶上nginx和版本號,我們把他隱藏起來

[root@localhost nginx-1.10.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 
;

2、安裝ngnix

[root@localhost ~]# groupadd www    #新增www組 
[root@localhost ~]# useradd -g www www -s /sbin/nologin    #建立nginx執行賬戶www並加入到www組,不允許www使用者直接登入系統 
[root@localhost nginx-1.10.2]# ./configure --prefix=/usr/local/nginx1.10 --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

相關選項說明

–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

如果pcre是通過編譯安裝的話,例如

# tar zxvf/usr/local/src/pcre-8.36.tar.gz -C /usr/local/src/ 
# cd  /usr/local/src/pcre-8.36 
# ./configure &&make && make install

則–with-pcre=/usr/local/src/pcre-8.36 #需要注意,這裡指的是原始碼,用#./configure –help | grep pcre檢視幫助

[root@localhost nginx-1.10.2]#ln-s /usr/local/nginx1.10/sbin/nginx /usr/local/sbin/ 
[root@localhost nginx-1.10.2]#nginx-t

啟動nginx

[root@localhost nginx-1.10.2]nginx 
[root@localhost nginx-1.10.2]# netstat -anpt | grep nginx 
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      7424/nginx: master

測試是否隱藏了版本和軟體名

[root@localhost nginx-1.10.2]# curl -I http://192.168.129.150 
HTTP/1.1 200 OK 
Server: IIS/7.0 
Date: Sat, 18 Mar 2017 02:16:41 GMT 
Content-Type: text/html 
Content-Length: 612 
Last-Modified: Sat, 18 Mar 2017 00:51:03 GMT 
Connection: keep-alive 
ETag: "58cc8477-264" 
Accept-Ranges: bytes 
[root@localhost nginx-1.10.2]# nginx -h 
nginx version: IIS/7.0 
Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives] 

Options: 
  -?,-h         : this help 
  -v            : show version and exit 
  -V            : show version and configure options then exit 
  -t            : test configuration and exit 
  -T            : test configuration, dump it and exit 
  -q            : suppress non-error messages during configuration testing 
  -s signal     : send signal to a master process: stop, quit, reopen, reload 
  -p prefix     : set prefix path (default: /usr/local/nginx1.10/) 
  -c filename   : set configuration file (default: conf/nginx.conf) 
  -g directives : set global directives out of configuration file

3、nginx配置項優化

[root@localhost nginx-1.10.2]# ps -ef | grep nginx 
root      7424     1  0 08:52 ?        00:00:00 nginx: master process nginx 
www      34878  7424  0 10:20 ?        00:00:00 nginx: worker process

在這裡我們還可以看到在檢視的時候,work程式是nginx程式使用者,但是master程式還是root,其中,master是監控程式,也叫主程式,work是工作程式,部分還有cache相關程式,關係如圖:

可以直接理解為master是管理員,work程式才是為使用者提供服務的!

(1):Nginx執行工作程式個數,一般我們設定CPU的核心或者核心數x2

如果不瞭解cpu的核數,可以top命令之後按1也可以看出來,也可以檢視/proc/cpuinfo檔案

[root@localhost nginx-1.10.2]# grep ^processor /proc/cpuinfo | wc -l 

2  
[root@localhost ~]#vi /usr/local/nginx1.10/conf/nginx.conf 
 worker_processes  4; 
[root@localhost ~]#/usr/local/nginx1.10/sbin/nginx -s reload 
[root@localhost ~]# ps -aux | grep nginx | grep -v grep 

root      7424  0.0  0.1 178828  3004 ?        Ss   08:52   0:00 nginx: master process nginx 

www      34878  0.0  1.5 207536 28880 ?        S    10:20   0:00 nginx: worker process 

www      34879  0.0  1.5 207536 28636 ?        S    10:20   0:00 nginx: worker process 

www      34880  0.0  1.5 207536 28636 ?        S    10:20   0:00 nginx: worker process 

www      34881  0.0  1.5 207536 28576 ?        S    10:20   0:00 nginx: worker process 

www      34882  0.0  0.1 180912  1908 ?        S    10:20   0:00 nginx: cache manager process

Nginx執行CPU親和力

比如4核配置

worker_processes  4; 

worker_cpu_affinity 0001 0010 0100 1000;

比如8核配置

worker_processes 8; 
worker_cpu_affinity 00000001 0000001000000100 00001000 00010000 00100000 01000000 10000000;

worker_processes最多開啟8個,8個以上效能提升不會再提升了,而且穩定性變得更低,所以8個程式夠用了

Nginx最多可以開啟檔案數

worker_rlimit_nofile 65535;

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

注:檔案資源限制的配置可以在/etc/security/limits.conf設定,針對root/user等各個使用者或者*代表所有使用者來設定。

*     soft   nofile  65535 
*    hard  nofile    65535

使用者重新登入生效(ulimit -n)

(2)Nginx事件處理模型

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

nginx採用epoll事件模型,處理效率高,work_connections是單個worker程式允許客戶端最大連線數,這個數值一般根據伺服器效能和記憶體來制定,實際最大值就是worker程式數乘以work_connections,實際我們填入一個65535,足夠了,這些都算併發值,一個網站的併發達到這麼大的數量,也算一個大站了!

multi_accept 告訴nginx收到一個新連線通知後接受盡可能多的連線,預設是on,設定為on後,多個worker按序列方式來處理連線,也就是一個連線只有一個worker被喚醒,其他的處於休眠狀態,設定為off後,多個worker按並行方式來處理連線,也就是一個連線會喚醒所有的worker,直到連線分配完畢,沒有取得連線的繼續休眠。當你的伺服器連線數不多時,開啟這個引數會讓負載有一定的降低,但是當伺服器的吞吐量很大時,為了效率,可以關閉這個引數。

(3)開啟高效傳輸模式

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

Include mime.types; //媒體型別,include 只是一個在當前檔案中包含另一個檔案內容的指令

default_typeapplication/octet-stream; //預設媒體型別足夠

sendfile on;//開啟高效檔案傳輸模式,sendfile指令指定nginx是否呼叫sendfile函式來輸出檔案,對於普通應用設為 on,如果用來進行下載等應用磁碟IO重負載應用,可設定為off,以平衡磁碟與網路I/O處理速度,降低系統的負載。

注意:如果圖片顯示不正常把這個改成off。

tcp_nopush on;必須在sendfile開啟模式才有效,防止網路阻塞,積極的減少網路報文段的數量(將響應頭和正文的開始部分一起傳送,而不一個接一個的傳送。)

(4)連線超時時間

主要目的是保護伺服器資源,CPU,記憶體,控制連線數,因為建立連線也是需要消耗資源的

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_size4k;客戶端請求頭部的緩衝區大小,這個可以根據你的系統分頁大小來設定,一般一個請求頭的大小不會超過 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上傳檔案大小限制

(5)fastcgi調優

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;

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的兩倍,該數值設定小時若負載上來時可能報502Bad Gateway

fastcgi_temp_path #快取臨時目錄

fastcgi_intercept_errors on;#這個指令指定是否傳遞4xx和5xx錯誤資訊到客戶端,或者允許nginx使用error_page處理錯誤資訊。

注:靜態檔案不存在會返回404頁面,但是php頁面則返回空白頁!!

fastcgi_cache_path /usr/local/nginx1.10/fastcgi_cachelevels=1:2 keys_zone=cache_fastcgi:128minactive=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_keyhttp://$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)的壓力。

(6)gzip調優

使用gzip壓縮功能,可能為我們節約頻寬,加快傳輸速度,有更好的體驗,也為我們節約成本,所以說這是一個重點。Nginx啟用壓縮功能需要你來ngx_http_gzip_module模組,apache使用的是mod_deflate一般我們需要壓縮的內容有:文字,js,html,css,對於圖片,視訊,flash什麼的不壓縮,同時也要注意,我們使用gzip的功能是需要消耗CPU的!

gzip on; 
gzip_min_length  2k; 
gzip_buffers    4 32k; 
gzip_http_version 1.1; 
gzip_comp_level   6; 
gzip_types   text/plaintext/css text/javascript application/json application/javascriptapplication/x-javascript application/xml; 
gzip_vary on; 
gzip_proxied any;

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/xmlapplication/javascript; #用來指定壓縮的型別,‘text/html’型別總是會被壓縮。

預設值: gzip_types text/html (預設不對js/css檔案進行壓縮)

# 壓縮型別,匹配MIME型別進行壓縮

# 不能用萬用字元 text/*

# (無論是否指定)text/html預設已經壓縮

# 設定哪壓縮種文字檔案可參考 conf/mime.types

gzip_vary on; #vary header支援,改選項可以讓前端的快取伺服器快取經過GZIP壓縮的頁面,例如用Squid快取經過nginx壓縮的資料

(7)expires快取調優

快取,主要針對於圖片,css,js等元素更改機會比較少的情況下使用,特別是圖片,佔用頻寬大,我們完全可以設定圖片在瀏覽器本地快取365d,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中記錄不存在的錯誤。預設是。

總結:

expire功能優點 (1)expires可以降低網站購買的頻寬,節約成本(2)同時提升使用者訪問體驗(3)減輕服務的壓力,節約伺服器成本,是web服務非常重要的功能。 expire功能缺點:被快取的頁面或資料更新了,使用者看到的可能還是舊的內容,反而影響使用者體驗。解決辦法:第一個縮短快取時間,例如:1天,但不徹底,除非更新頻率大於1天;第二個對快取的物件改名。

網站不希望被快取的內容 1)網站流量統計工具2)更新頻繁的檔案(google的logo)

(8)防盜鏈

防止別人直接從你網站引用圖片等連結,消耗了你的資源和網路流量,那麼我們的解決辦法由幾種: 1:水印,品牌宣傳,你的頻寬,伺服器足夠 2:防火牆,直接控制,前提是你知道IP來源 3:防盜鏈策略下面的方法是直接給予404的錯誤提示

location ~*^.+\.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ { 
    valid_referers none blocked www.benet.com benet.com; 
    if ($invalid_referer) { 
      #return 302 http://www.benet.com/img/nolink.jpg; 
      return 404; 
       break; 
    } 
    access_log off; 
 }

引數可以使如下形式:

none 意思是不存在的Referer頭(表示空的,也就是直接訪問,比如直接在瀏覽器開啟一個圖片)

blocked 意為根據防火牆偽裝Referer頭,如:“Referer: XXXXXXX”。

server_names 為一個或多個伺服器的列表,0.5.33版本以後可以在名稱中使用“*”萬用字元。

(9)核心引數優化

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-WAITsockets重新用於新的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 = 1024087380 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攻擊。

下面貼一個完整的核心優化設定:

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

執行sysctl -p使核心修改生效

(10)關於系統連線數的優化:

linux 預設值 open files為1024

[root@localhost ~]# ulimit -n  

1024

說明server只允許同時開啟1024個檔案

使用ulimit -a 可以檢視當前系統的所有限制值,使用ulimit -n 可以檢視當前的最大開啟檔案數。

新裝的linux 預設只有1024 ,當作負載較大的伺服器時,很容易遇到error: too many open files。因此,需要將其改大

在/etc/security/limits.conf最後增加:

*                soft    nofile          65535 
*                hard    nofile          65535 
*                soft    noproc          65535 
*                hard    noproc          65535

二、部署LNMP

1、安裝php

(1)解決依賴關係

[root@localhost ~]#yum -y install libxml2-devel libcurl-devel openssl-devel bzip2-devel

安裝libmcrypt

[root@localhost ~]#tar zxf libmcrypt-2.5.7.tar.gz 
[root@localhost ~]# cd libmcrypt-2.5.7/ 
[root@localhost libmcrypt-2.5.7]# ./configure --prefix=/usr/local/libmcrypt && make && make install

(2)編譯安裝php

[root@localhost ~]#tar zxf php-5.6.27.tar.gz 
[root@localhost ~]# cd php-5.6.27/ 
[root@localhost php-5.6.27]# ./configure --prefix=/usr/local/php5.6 --with-mysql=mysqlnd --with-pdo-mysql=mysqlnd --with-mysqli=mysqlnd --with-openssl --enable-fpm --enable-sockets --enable-sysvshm --enable-mbstring --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir=/usr --enable-xml --with-mhash --with-mcrypt=/usr/local/limcrypt --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --with-bz2--enable-maintainer-zts && make && make install

(3)提供php配置檔案

[root@localhost php-5.6.27]#cp php.ini-production /etc /php.ini

(4)為php-fpm提供指令碼

[root@localhost php-5.6.27]#cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm 
[root@localhost php-5.6.27]#chmod +x /etc/init.d/php-fpm 
[root@localhost php-5.6.27]#chkconfig --add php-fpm 
[root@localhost php-5.6.27]#chkconfig php-fpm on

(5)提供php-fpm配置檔案並編輯:

[root@localhost php-5.6.27]#cp /usr/local/php5.6/etc/php-fpm.conf.default /usr/local/php5.6/etc/php-fpm.conf 
[root@localhost php-5.6.27]#vi /usr/local/php5.6/etc/php-fpm.conf

修改內容如下:

pid = run/php-fpm.pid 
listen = 0.0.0.0:9000 
pm.max_children =300 
pm.start_servers =20 
pm.min_spare_servers = 20 
pm.max_spare_servers= 100

啟動php-fpm服務:

[root@localhost php-5.6.27]#service  php-fpm start 
Starting php-fpm  done 
[root@localhost php-5.6.27]# netstat -anpt | grep php-fpm 

tcp        0      0 0.0.0.0:9000            0.0.0.0:*               LISTEN      33807/php-fpm: mast 
[root@localhost php-5.6.27]#firewall-cmd --permanent --add-port=9000/tcp 
success 
[root@localhost php-5.6.27]#firewall-cmd --reloadl 
success

在nginx.conf檔案的server中新增下面內容支援php

location ~ .*\.(php|php5)?$ { 
            root html; 
            fastcgi_pass 127.0.0.1:9000; 
            fastcgi_index index.php; 
            include fastcgi.conf; 
            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_use_stale errortimeout invalid_header http_500; 
            fastcgi_cache_keyhttp://$host$request_uri; 
}

下面是nginx.conf的一個完整配置檔案

user www www; 
worker_processes  4; 
worker_cpu_affinity 0001 0010 0100 1000; 
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  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:2keys_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/csstext/javascript application/json application/javascriptapplication/x-javascript application/xml; 
   gzip_vary on; 
   gzip_proxied any; 
server { 
       listen       80; 
       server_name  www.benet.com; 

       #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  www.benet.com benet.com; 
            if ($invalid_referer) { 
                #return 302  http://www.benet.com/img/nolink.jpg; 
                return 404; 
                break; 
             } 
             access_log off; 
       } 
       location / { 
            root   html; 
             index  index.php 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; 
       }       

       location = /(favicon.ico|roboots.txt) { 
            access_log off; 
            log_not_found off; 
       } 
       location /status { 
            stub_status on; 
       } 
       location ~ .*\.(php|php5)?$ { 
            root html; 
            fastcgi_pass 127.0.0.1:9000; 
            fastcgi_index index.php; 
            include fastcgi.conf; 
            fastcgi_cache cache_fastcgi; 
           fastcgi_cache_valid 200 3021h; 
            fastcgi_cache_valid 301 1d; 
            fastcgi_cache_valid any 1m; 
            fastcgi_cache_min_uses 1; 
            fastcgi_cache_use_stale errortimeout invalid_header http_500; 
            fastcgi_cache_keyhttp://$host$request_uri; 
       } 
       #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; 
       } 
  } 
}

過載nginx服務

[root@localhost ~]# /usr/local/nginx1.10/sbin/nginx -s reload

三、驗證、壓力測試

(1)驗證防盜鏈

使用apache做為一個測試站點,域名為www.test.com,在測試頁上做一個超連結,連結nginx站點的一張圖片

[root@centos1 ~]# cat/var/www/html/index.html  
<a href="http://www.benet.com/11.gif">lianjie</a>

Nginx站點的網頁目錄結如下

[root@localhost ~]# tree /usr/local/nginx1.10/html/ 

/usr/local/nginx1.10/html/ 

├── 11.gif 

├── 50x.html 

├── img 

│   └── nolink.jpg 

├── index.html 

├── test.php

在客戶端瀏覽器中輸入www.test.com (注意域名解析和防火牆)

在客戶端瀏覽器中輸入www.test.com

點選頁面連結

點選頁面連結

從上圖可以看到防盜鏈設定生效了

(2)驗證gzip功能

使用谷歌瀏覽器測試訪問,如下圖顯示結果:(提示:在訪問測試頁之前按F12鍵)

使用谷歌瀏覽器測試訪問

使用者訪問test.php檔案,在上圖中content-encoding:gzip表明響應給使用者的資料是壓縮傳輸。

(3)壓力測試

安裝httpd-tools軟體包

[root@localhost ~]# yum -y install httpd-tools 
 [root@localhost ~]# ab -c 500 -n 50000 http://192.168.129.150/index.html 
This is ApacheBench, Version 2.3 <$Revision: 1430300 $> 
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ 
Licensed to The Apache Software Foundation, http://www.apache.org/ 
Benchmarking 192.168.129.150 (be patient) 
Completed 5000 requests 
Completed 10000 requests 
Completed 15000 requests 
Completed 20000 requests 
Completed 25000 requests 
Completed 30000 requests 
Completed 35000 requests 
Completed 40000 requests 
Completed 45000 requests 
Completed 50000 requests 
Finished 50000 requests 

Server Software:        IIS 
Server Hostname:        192.168.129.150 
Server Port:            80 
Document Path:          /index.html 
Document Length:        612 bytes 
Concurrency Level:      500 
Time taken for tests:   3.607 seconds 
Complete requests:      50000 
Failed requests:        0 
Write errors:           0 
Total transferred:      41800000 bytes 
HTML transferred:       30600000 bytes 
Requests per second:    13862.78 [#/sec] (mean) 
Time per request:       36.068 [ms] (mean) 
Time per request:       0.072 [ms] (mean, across all concurrent requests) 
Transfer rate:          11317.66 [Kbytes/sec] received 
Connection Times (ms) 
              min  mean[+/-sd] median   max 
Connect:        0   16  25.5     15    1013 
Processing:     4   18   4.1     18      71 
Waiting:        1   14   4.3     12      36 
Total:         17   34  25.7     34    1032 
Percentage of the requests served within a certain time (ms) 
  50%     34 
  66%     35 
  75%     35 
  80%     36 
  90%     37 
  95%     37 
  98%     38 
  99%     64 
 100%   1032 (longest request)

第二次壓力測試,比較兩次的差異

[root@localhost ~]# ab -c 1000 -n 100000 http://192.168.129.150/index.html 
This is ApacheBench, Version 2.3 <$Revision: 1430300 $> 
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ 
Licensed to The Apache Software Foundation, http://www.apache.org/ 
Benchmarking 192.168.129.150 (be patient) 
Completed 10000 requests 
Completed 20000 requests 
Completed 30000 requests 
Completed 40000 requests 
Completed 50000 requests 
Completed 60000 requests 
Completed 70000 requests 
Completed 80000 requests 
Completed 90000 requests 
Completed 100000 requests 
Finished 100000 requests 

Server Software:        IIS 
Server Hostname:        192.168.129.150 
Server Port:            80 
Document Path:          /index.html 
Document Length:        612 bytes 
Concurrency Level:      1000 
Time taken for tests:   7.332 seconds 
Complete requests:      100000 
Failed requests:        0 
Write errors:           0 
Total transferred:      83600000 bytes 
HTML transferred:       61200000 bytes 
Requests per second:    13638.90 [#/sec] (mean) 
Time per request:       73.320 [ms] (mean) 
Time per request:       0.073 [ms] (mean, across all concurrent requests) 
Transfer rate:          11134.88 [Kbytes/sec] received 
Connection Times (ms) 
              min  mean[+/-sd] median   max 
Connect:        0   40 114.5     27    1046 
Processing:     7   32   9.4     33     237 
Waiting:        1   24   8.8     23     232 
Total:         29   72 115.3     62    1075 
Percentage of the requests served within a certain time (ms) 
  50%     62 
  66%     69 
  75%     71 
  80%     72 
  90%     75 
  95%     76 
  98%     80 
  99%   1056 
 100%   1075 (longest request)

(5)xcache加速php

安裝xcache

wget    #下載 
[root@localhost ~]#tar zxfxcache-3.2.0.tar.gz  #解壓 
[root@localhost ~]# cd xcache-3.2.0/           #進入安裝目錄 
[root@localhost xcache-3.2.0]# /usr/local/php5.6/bin/phpize#用phpize生成configure配置檔案 
[root@localhost xcache-3.2.0]# ./configure --enable-xcache --enable-xcache-coverager --enable-xcache-optimizer --with-php-config=/usr/local/php5.6/bin/php-config   #配置 
[root@localhost xcache-3.2.0]# make && make install     #編譯、安裝 
Installing sharedextensions:                 /usr/local/php5.6/lib/php/extensions/no-debug-non-zts-20131226/

安裝完成之後,出現下面的介面,記住以下路徑,後面會用到

/usr/local/php5.6/lib/php/extensions/no-debug-non-zts-20131226/

2)建立xcache快取檔案

# touch /tmp/xcache 
# chmod 777 /tmp/xcache

3)拷貝xcache後臺管理程式到網站根目錄

[root@localhost xcache-3.2.0]# cp -r htdocs/ /usr/local/nginx1.10/html/xcache

4)配置php支援xcache

vi / etc/php.ini #編輯配置檔案,在最後一行新增以下內容

[xcache-common] 
extension =/usr/local/php5.6/lib/php/extensions/no-debug-non-zts-20131226/xcache.so 
[xcache.admin] 
xcache.admin.enable_auth = Off 
[xcache] 
xcache.shm_scheme ="mmap" 
xcache.size=60M 
xcache.count =1 
xcache.slots =8K 
xcache.ttl=0 
xcache.gc_interval =0 
xcache.var_size=64M 
xcache.var_count =1 
xcache.var_slots =8K 
xcache.var_ttl=0 
xcache.var_maxttl=0 
xcache.var_gc_interval =300 
xcache.test =Off 
xcache.readonly_protection = Off 
xcache.mmap_path="/tmp/xcache" 
xcache.coredump_directory ="" 
xcache.cacher =On 
xcache.stat=On 
xcache.optimizer =Off 
[xcache.coverager] 
xcache.coverager =On 
xcache.coveragedump_directory=""

測試

service php-fpm restart #重啟php-fpm

瀏覽器開啟網站根目錄下面的xcache

http://www.benet.com/xcache可以看到如下頁面:

測試對php動態頁面的壓力測試

[root@localhost xcache-3.2.0]# ab -c 1000 -n 100000 http://192.168.129.150/test.php 
This is ApacheBench, Version 2.3 <$Revision: 1430300 $> 
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ 
Licensed to The Apache Software Foundation, http://www.apache.org/ 

Benchmarking 192.168.129.150 (be patient) 
Completed 10000 requests 
Completed 20000 requests 
Completed 30000 requests 
Completed 40000 requests 
Completed 50000 requests 
Completed 60000 requests 
Completed 70000 requests 
Completed 80000 requests 
Completed 90000 requests 
Completed 100000 requests 
Finished 100000 requests 

Server Software:        IIS 
Server Hostname:        192.168.129.150 
Server Port:            80 

Document Path:          /test.php 
Document Length:        16 bytes 

Concurrency Level:      1000 
Time taken for tests:   7.031 seconds 
Complete requests:      100000 
Failed requests:        0 
Write errors:           0 
Non-2xx responses:      100000 
Total transferred:      20000000 bytes 
HTML transferred:       1600000 bytes 
Requests per second:    14223.52 [#/sec] (mean) 
Time per request:       70.306 [ms] (mean) 
Time per request:       0.070 [ms] (mean, across all concurrent requests) 
Transfer rate:          2778.03 [Kbytes/sec] received 

Connection Times (ms) 
              min  mean[+/-sd] median   max 
Connect:        0   39 133.7     20    1035 
Processing:     4   27  12.4     26     238 
Waiting:        0   20   9.6     18     227 
Total:         17   65 135.7     50    1254 

Percentage of the requests served within a certain time (ms) 
  50%     50 
  66%     54 
  75%     57 
  80%     59 
  90%     62 
  95%     65 
  98%    213 
  99%   1047 
 100%   1254 (longest request)

主要引數說明:

Requests per second:平均每秒處理事務數

Time per request:平均事務響應時間

Tranfer rate:平均每秒網路吞吐量

相關文章