Nginx優化與防盜鏈

一、 Nginx 的優化
1、 編譯安裝前優化
編譯前的優化主要是用來修改程序名等等, 目的更改源碼隱藏軟件名稱和版本號
安裝 zlib-devel、 pcre-devel 等依賴包
[root@www ~]# yum -y install gcc gcc-c++ make libtool zlib zlib-devel pcre pcre-devel openssl
openssl-devel
下載 nginx 的源碼包: http://nginx.org/download
解壓源碼包:
[root@www ~]# tar zxf nginx-1.10.2.tar.gz
[root@www ~]# cd nginx-1.10.2/
隱藏軟件名稱和版本號
[root@www nginx-1.10.2]# vim src/core/nginx.h
//此行修改的是你想要的版本
#define NGINXVERSION "1.10.2" //第 13 行
//此行修改的是你想修改的軟件名稱
#define NGINXVER "nginx/" NGINXVERSION //第 14 行
修改上面的信息, 即可更改 nginx 顯示版本。 例如: (curl –I 可看到, 請求頭和響應頭顯示)
#define NGINXVERSION "7.0"
#define NGINXVER "IIS/" NGINXVERSION
修改 HTTP 頭信息中的 connection 字段,防止回顯具體版本號
拓展:通用 http 頭 , 通用頭包含請求和響應消息都支持的頭,通用頭包含 Cache-Control、
Connection、 Date、 Pragma、 Transfer-Encoding、 Upgrade、 Via。對通用頭的擴展要求通訊雙
方都支持此擴展,如果存在不支持的通用頭,一般將會作爲實體頭處理。那麼也就是說有部
分設備,或者是軟件,能獲取到 connection,部分不能,要隱藏就要徹底!
[root@www nginx-1.10.2]# vi src/http/ngxhttpheaderfiltermodule.c
修改前:
static char ngxhttpserverstring[] = "Server: nginx" CRLF; //第 49 行
修改後:
static char ngxhttpserverstring[] = "Server: IIS" CRLF;
定義了 http 錯誤碼的返回:
有時候我們頁面程序出現錯誤, Nginx 會代我們返回相應的錯誤代碼,回顯的時候,會帶上
nginx 和版本號,我們把他隱藏起來
[root@www nginx-1.10.2]# vi src/http/ngxhttpspecialresponse.c
修改前
static uchar ngxhttperrortail[] = //第 29 行
"<hr><center>nginx</center>" CRLF
"</body>" CRLF
"</html>" CRLF
;
修改後
static uchar ngxhttperrortail[] =
"<hr><center>IIS</center>" CRLF
"</body>" CRLF
"</html>" CRLF
;

2、安裝 ngnix
[root@www ~]# groupadd www #添加 www 組
[root@www ~]# useradd -g www www -s /sbin/nologin #創建 nginx運行賬戶 www並加入到
www 組,不允許 www 用戶直接登錄系統
[root@www nginx-1.10.2]# ./configure --prefix=/usr/local/nginx1.10
--with-httpdavmodule --with-httpstubstatusmodule
--with-httpadditionmodule --with-httpsubmodule
--with-httpflvmodule --with-httpmp4module --with-pcre
--with-httpsslmodule --with-httpgzipstaticmodule
--user=www --group=www
[root@www nginx-1.10.2]# make && make install
相關選項說明
--with-httpdavmodule #增加 PUT,DELETE,MKCOL:創建集合, COPY 和 MOVE 方法
--with-httpstubstatusmodule #獲取 Nginx 的狀態統計信息
--with-httpadditionmodule #作爲一個輸出過濾器,支持不完全緩衝,分部分相應請求
--with-httpsubmodule #允許一些其他文本替換 Nginx 相應中的一些文本
--with-httpflvmodule #提供支持 flv 視頻文件支持
--with-httpmp4module #提供支持 mp4 視頻文件支持,提供僞流媒體服務端支持
--with-httpsslmodule #啓用 ngxhttpsslmodule
如果 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@www nginx-1.10.2]# ln -s /usr/local/nginx1.10/sbin/nginx /usr/local/sbin/
[root@www nginx-1.10.2]# nginx -t
啓動 nginx
[root@www nginx-1.10.2]# nginx
[root@www nginx-1.10.2]# netstat -anpt | grep nginx
tcp 0 0 0.0.0.0:80 0.0.0.0: LISTEN 9834/nginx: master
測試是否隱藏了版本和軟件名
[root@www ~]# curl -I http://127.0.0.1
HTTP/1.1 200 OK
Server: IIS/7.0

Date: Sat, 05 Nov 2016 14:38:21 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Sat, 05 Nov 2016 14:19:47 GMT
Connection: keep-alive
ETag: "581dea83-264"
Accept-Ranges: bytes
[root@www ~]# nginx -h
nginx version: IIS/7.0
Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]
Options:
-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@www ~]# ps -ef | grep nginx

root 9834 1 0 22:36 ? 00:00:00 nginx: master process nginx
www 9953 9834 0 22:43 ? 00:00:00 nginx: worker process
在這裏我們還可以看到在查看的時候, work 進程是 nginx 程序用戶,但是 master 進程還是
root, 其中, master 是監控進程,也叫主進程, work 是工作進程,部分還有 cache 相關進程,
關係如圖:

Nginx優化與防盜鏈

可以直接理解爲 master 是管理員, work 進程纔是爲用戶提供服務的!
(1):Nginx 運行工作進程個數,一般我們設置 CPU 的核心或者核心數 x2
如果不瞭解 cpu 的核數, 可以 top 命令之後按 1 也可以看出來,也可以查看/proc/cpuinfo 文
件#grep ^processor /proc/cpuinfo | wc -l
[root@www ~]# vi /usr/local/nginx1.10/conf/nginx.conf
workerprocesses 4;
[root@www ~]# /usr/local/nginx1.10/sbin/nginx -s reload
[root@www ~]# ps -aux | grep nginx | grep -v grep
root 9834 0.0 0.0 47556 1948 ? Ss 22:36 0:00 nginx: master process nginx
www 10135 0.0 0.0 50088 2004 ? S 22:58 0:00 nginx: worker process
www 10136 0.0 0.0 50088 2004 ? S 22:58 0:00 nginx: worker process
www 10137 0.0 0.0 50088 2004 ? S 22:58 0:00 nginx: worker process
www 10138 0.0 0.0 50088 2004 ? S 22:58 0:00 nginx: worker process
Nginx 運行 CPU 親和力
比如 4 核配置
workerprocesses 4;
workercpuaffinity 0001 0010 0100 1000
比如 8 核配置
workerprocesses 8;
workercpuaffinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000
10000000;
workerprocesses 最多開啓 8 個, 8 個以上性能提升不會再提升了,而且穩定性變得更低,
所以 8 個進程夠用了。
Nginx 最多可以打開文件數
workerrlimitnofile 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;
workerconnections 65535;
multiaccept on;
}
nginx 採用 epoll 事件模型,處理效率高
workconnections 是單個 worker 進程允許客戶端最大連接數,這個數值一般根據服務器性
能和內存來制定,實際最大值就是 worker 進程數乘以 workconnections
實際我們填入一個 65535,足夠了,這些都算併發值,一個網站的並發達到這麼大的數量,
也算一個大站了!
multiaccept 告訴 nginx 收到一個新連接通知後接受儘可能多的連接
(3)開啓高效傳輸模式
http {
include mime.types;
defaulttype application/octet-stream;
……
sendfile on;
tcpnopush on;
……
Include mime.types; //媒體類型, include 只是一個在當前文件中包含另一個文件內容的指令
defaulttype application/octet-stream; //默認媒體類型足夠
sendfile on; //開啓高效文件傳輸模式, sendfile 指令指定 nginx 是否調用 sendfile 函數來
輸出文件,對於普通應用設爲 on,如果用來進行下載等應用磁盤 IO 重負載應用,可設置爲
off,以平衡磁盤與網絡 I/O 處理速度,降低系統的負載。
注意:如果圖片顯示不正常把這個改成 off。
tcpnopush on; 必須在 sendfile 開啓模式纔有效,防止網路阻塞,積極的減少網絡報文
段的數量(告訴 nginx 在一個數據包裏發送所有頭文件,而不一個接一個的發送。)
(4)連接超時時間
主要目的是保護服務器資源, CPU,內存,控制連接數,因爲建立連接也是需要消耗資源的
keepalivetimeout 60;
tcpnodelay on;
clientheaderbuffersize 4k;
openfilecache max=102400 inactive=20s;
openfilecachevalid 30s;
openfilecacheminuses 1;
clientheadertimeout 15;
clientbodytimeout 15;
resettimedoutconnection on;
sendtimeout 15;
servertokens off;
clientmaxbodysize 10m;
keepalivedtimeout 客戶端連接保持會話超時時間,超過這個時間,服務器斷開這個鏈接
tcpnodelay;也是防止網絡阻塞,不過要包涵在 keepalived 參數纔有效
clientheaderbuffersize 4k;
客戶端請求頭部的緩衝區大小,這個可以根據你的系統分頁大小來設置,一般一個請求頭的
大小不會超過 1k,不過由於一般系統分頁都要大於 1k,所以這裏設置爲分頁大小。分頁大
小可以用命令 getconf PAGESIZE 取得。
openfilecache max=102400 inactive=20s;
這個將爲打開文件指定緩存,默認是沒有啓用的, max 指定緩存數量,建議和打開文件
數一致, inactive 是指經過多長時間文件沒被請求後刪除緩存。
openfilecachevalid 30s;
這個是指多長時間檢查一次緩存的有效信息。
openfilecacheminuses 1;
openfilecache 指令中的 inactive 參數時間內文件的最少使用次數,如果超過這個數字,文
件描述符一直是在緩存中打開的,如上例,如果有一個文件在 inactive 時間內一次沒被使用,
它將被移除。
clientheadertimeout 設置請求頭的超時時間。我們也可以把這個設置低些,如果超過這個
時間沒有發送任何數據, nginx 將返回 request time out 的錯誤
clientbodytimeout 設置請求體的超時時間。我們也可以把這個設置低些,超過這個時間沒
有發送任何數據,和上面一樣的錯誤提示
resettimeoutconnection 告訴 nginx 關閉不響應的客戶端連接。這將會釋放那個客戶端所
佔有的內存空間。
sendtimeout 響應客戶端超時時間,這個超時時間僅限於兩個活動之間的時間,如果超過
這個時間,客戶端沒有任何活動, nginx 關閉連接
servertokens 並不會讓 nginx 執行的速度更快,但它可以關閉在錯誤頁面中的 nginx 版本
數字,這樣對於安全性是有好處的。
clientmaxbodysize 上傳文件大小限制
(5)fastcgi 調優
fastcgiconnecttimeout 600;
fastcgisendtimeout 600;
fastcgireadtimeout 600;
fastcgibuffersize 64k;
fastcgibuffers 4 64k;
fastcgibusybufferssize 128k;
fastcgitempfilewritesize 128k;
fastcgitemppath /usr/local/nginx1.10/nginxtmp;
fastcgiintercepterrors on;
fastcgicachepath /usr/local/nginx1.10/fastcgicache levels=1:2 keyszone=cachefastcgi:128m
inactive=1d maxsize=10g;
Cache: 寫入緩存區
Buffer: 讀取緩存區
Fastcgi 是靜態服務和動態服務的一個接口
fastcgiconnecttimeout 600; #指定連接到後端 FastCGI 的超時時間。
fastcgisendtimeout 600; #向 FastCGI 傳送請求的超時時間。
fastcgireadtimeout 600; #指定接收 FastCGI 應答的超時時間。
fastcgibuffersize 64k; #指定讀取 FastCGI 應答第一部分需要用多大的緩衝區, 默認的緩衝區
大小爲 fastcgibuffers 指令中的每塊大小,可以將這個值設置更小。
fastcgibuffers 4 64k; #指定本地需要用多少和多大的緩衝區來緩衝 FastCGI 的應答請求,如果
一個 php 腳本所產生的頁面大小爲 256KB,那麼會分配 4 個 64KB 的緩衝區來緩存,如果頁
面大小大於 256KB,那麼大於 256KB 的部分會緩存到 fastcgitemppath 指定的路徑中,但是
這並不是好方法,因爲內存中的數據處理速度要快於磁盤。一般這個值應該爲站點中 php
腳本所產生的頁面大小的中間值,如果站點大部分腳本所產生的頁面大小爲 256KB,那麼可
以把這個值設置爲“8 32K”、 “4 64k”等。
fastcgibusybufferssize 128k; #建議設置爲 fastcgibuffers 的兩倍,繁忙時候的 buffer
fastcgitempfilewritesize 128k; #在寫入 fastcgitemppath 時將用多大的數據塊,默認
值是 fastcgibuffers 的兩倍, 該數值設置小時若負載上來時可能報 502 Bad Gateway
fastcgitemppath #緩存臨時目錄
fastcgiintercepterrors on;# 這個指令指定是否傳遞 4xx 和 5xx 錯誤信息到客戶端,或者允許
nginx 使用 errorpage 處理錯誤信息。
注: 靜態文件不存在會返回 404 頁面,但是 php 頁面則返回空白頁!!
fastcgicachepath /usr/local/nginx1.10/fastcgicache levels=1:2 keyszone=cachefastcgi:128m
inactive=1d maxsize=10g; # fastcgicache 緩存目錄,可以設置目錄層級,比如 1:2 會生成
16256 個子目錄, cachefastcgi 是這個緩存空間的名字, cache 是用多少內存(這樣熱門的
內容 nginx 直接放內存,提高訪問速度), inactive 表示默認失效時間, 如果緩存數據在失效
時間內沒有被訪問,將被刪除, maxsize 表示最多用多少硬盤空間。
fastcgicache cachefastcgi; #表示開啓 FastCGI 緩存併爲其指定一個名稱。開啓緩存非常有
用,可以有效降低 CPU 的負載,並且防止 502 的錯誤放生。cachefastcgi 爲 proxycachepath
指令創建的緩存區名稱
fastcgicachevalid 200 302 1h; #用來指定應答代碼的緩存時間,實例中的值表示將 200 和
302 應答緩存一小時,要和 fastcgicache 配合使用
fastcgicachevalid 301 1d; #將 301 應答緩存一天
fastcgicachevalid any 1m; #將其他應答緩存爲 1 分鐘
fastcgicacheminuses 1; #該指令用於設置經過多少次請求的相同 URL 將被緩存。
fastcgicachekey http://$host$requesturi; #該指令用來設置 web緩存的 Key值,nginx根據 Key

值 md5 哈希存 儲 .一 般根 據 $host( 域名 )、 $requesturi(請 求的路 徑 ) 等變 量組 合成
proxycachekey 。
fastcgipass #指定 FastCGI 服務器監聽端口與地址,可以是本機或者其它
總結:
nginx 的緩存功能有: proxycache / fastcgicache
proxycache 的作用是緩存後端服務器的內容,可能是任何內容,包括靜態的和動態。
fastcgicache 的作用是緩存 fastcgi 生成的內容,很多情況是 php 生成的動態的內容。
proxycache 緩存減少了 nginx 與後端通信的次數,節省了傳輸時間和後端寬帶。
fastcgicache 緩存減少了 nginx 與 php 的通信的次數,更減輕了 php 和數據庫(mysql)的壓力。
(6)gzip 調優
使用 gzip 壓縮功能,可能爲我們節約帶寬,加快傳輸速度,有更好的體驗,也爲我們節約
成本,所以說這是一個重點。
Nginx 啓用壓縮功能需要你來 ngxhttpgzipmodule 模塊, apache 使用的是 moddeflate
一般我們需要壓縮的內容有:文本, js, html, css,對於圖片,視頻, flash 什麼的不壓縮,
同時也要注意,我們使用 gzip 的功能是需要消耗 CPU 的!
gzip on;
gzipminlength 2k;
gzipbuffers 4 32k;
gziphttpversion 1.1;
gzipcomplevel 6;
gziptypes text/plain text/css text/javascript application/json application/javascript
application/x-javascript application/xml;
gzipvary on;
gzipproxied any;
gzip on; #開啓壓縮功能
gzipminlength 1k; #設置允許壓縮的頁面最小字節數,頁面字節數從 header 頭的
Content-Length 中獲取,默認值是 0,不管頁面多大都進行壓縮,建議設置成大於 1K,如果
小與 1K 可能會越壓越大。
gzipbuffers 4 32k; #壓縮緩衝區大小,表示申請 4個單位爲 32K的內存作爲壓縮結果流緩存,
默認值是申請與原始數據大小相同的內存空間來存儲 gzip 壓縮結果。
gziphttpversion 1.1; #壓縮版本, 用於設置識別 HTTP 協議版本,默認是 1.1,目前大部分瀏
覽器已經支持 GZIP 解壓,使用默認即可
gzipcomplevel 6; #壓縮比例,用來指定 GZIP 壓縮比, 1 壓縮比最小,處理速度最快, 9 壓
縮比最大,傳輸速度快,但是處理慢,也比較消耗 CPU 資源。
gziptypes text/css text/xml application/javascript; #用來指定壓縮的類型, ‘text/html’類型總是
會被壓縮。
默認值: gziptypes text/html (默認不對 js/css 文件進行壓縮)
#壓縮類型,匹配 MIME 類型進行壓縮
#不能用通配符 text/
#(無論是否指定)text/html 默認已經壓縮
#設置哪壓縮種文本文件可參考 conf/mime.types
gzipvary 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;
#lognotfound off;
accesslog off;
}
location ~ .(js|css)$ {
expires 7d;
lognotfound off;
accesslog off;
}
注: lognotfound off;是否在 errorlog 中記錄不存在的錯誤。默認是。
總結:
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)$ {
validreferers none blocked www.benet.com benet.com;
if ($invalidreferer) {
#return 302 http://www.benet.com/img/nolink.jpg;
return 404;
break;
}
accesslog off;
}
(9)內核參數優化
fs.file-max = 999999:這個參數表示進程(比如一個 worker 進程)可以同時打開的最大句柄
數,這個參數直線限制最大併發連接數,需根據實際情況配置。
net.ipv4.tcpmaxtwbuckets = 6000 #這個參數表示操作系統允許 TIMEWAIT 套接字數量
的最大值,如果超過這個數字, TIMEWAIT 套接字將立刻被清除並打印警告信息。該參數默
認爲 180000,過多的 TIMEWAIT 套接字會使 Web 服務器變慢。
注: 主動關閉連接的服務端會產生 TIMEWAIT 狀態的連接
net.ipv4.iplocalportrange = 1024 65000 #允許系統打開的端口範圍。
net.ipv4.tcptwrecycle = 1 #啓用 timewait 快速回收。
net.ipv4.tcptwreuse = 1 #開啓重用。允許將 TIME-WAIT sockets 重新用於新的 TCP 連接。 這
對於服務器來說很有意義,因爲服務器上總會有大量 TIME-WAIT 狀態的連接。
net.ipv4.tcpkeepalivetime = 30:這個參數表示當 keepalive 啓用時, TCP 發送 keepalive 消息
的頻度。默認是 2 小時,若將其設置的小一些,可以更快地清理無效的連接。
net.ipv4.tcpsyncookies = 1 #開啓 SYN Cookies,當出現 SYN 等待隊列溢出時,啓用 cookies 來
處理。
net.core.somaxconn = 40960 #web 應用中 listen 函數的 backlog 默認會給我們內核參數的
net.core.somaxconn 限制到 128,而 nginx 定義的 NGXLISTENBACKLOG 默認爲 511,所以
有必要調整這個值。
注: 對於一個 TCP 連接, Server 與 Client 需要通過三次握手來建立網絡連接.當三次握手成功
後,我們可以看到端口的狀態由 LISTEN 轉變爲 ESTABLISHED,接着這條鏈路上就可以開始傳送
數據了.每一個處於監聽(Listen)狀態的端口,都有自己的監聽隊列.監聽隊列的長度與如
somaxconn 參數和使用該端口的程序中 listen()函數有關
somaxconn 參數:定義了系統中每一個端口最大的監聽隊列的長度,這是個全局的參數,默認值
爲 128, 對於一個經常處理新連接的高負載 web 服務環境來說,默認的 128 太小了。大多
數環境這個值建議增加到 1024 或者更多。大的偵聽隊列對防止拒絕服務 DoS ***也會有
所幫助。
net.core.netdevmaxbacklog = 262144 #每個網絡接口接收數據包的速率比內核處理這些包
的速率快時,允許送到隊列的數據包的最大數目。
net.ipv4.tcpmaxsynbacklog = 262144 #這個參數標示 TCP 三次握手建立階段接受 SYN 請求
隊列的最大長度,默認爲 1024,將其設置得大一些可以使出現 Nginx 繁忙來不及 accept 新
連接的情況時, Linux 不至於丟失客戶端發起的連接請求。
net.ipv4.tcprmem = 10240 87380 12582912#這個參數定義了 TCP 接受緩存(用於 TCP 接
受滑動窗口)的最小值、默認值、最大值。
net.ipv4.tcpwmem = 10240 87380 12582912:這個參數定義了 TCP 發送緩存(用於 TCP 發送
滑動窗口)的最小值、默認值、最大值。
net.core.rmemdefault = 6291456:這個參數表示內核套接字接受緩存區默認的大小。
net.core.wmemdefault = 6291456:這個參數表示內核套接字發送緩存區默認的大小。
net.core.rmemmax = 12582912:這個參數表示內核套接字接受緩存區的最大大小。
net.core.wmemmax = 12582912:這個參數表示內核套接字發送緩存區的最大大小。
net.ipv4.tcpsyncookies = 1:該參數與性能無關,用於解決 TCP 的 SYN ***。
下面貼一個完整的內核優化設置:
fs.file-max = 999999
net.ipv4.ipforward = 0
net.ipv4.conf.default.rpfilter = 1
net.ipv4.conf.default.acceptsourceroute = 0
kernel.sysrq = 0
kernel.coreusespid = 1
net.ipv4.tcpsyncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
net.ipv4.tcpmaxtwbuckets = 6000
net.ipv4.tcpsack = 1
net.ipv4.tcpwindowscaling = 1
net.ipv4.tcprmem = 10240 87380 12582912
net.ipv4.tcpwmem = 10240 87380 12582912
net.core.wmemdefault = 8388608
net.core.rmemdefault = 8388608
net.core.rmemmax = 16777216
net.core.wmemmax = 16777216
net.core.netdevmaxbacklog = 262144
net.core.somaxconn = 40960
net.ipv4.tcpmaxorphans = 3276800
net.ipv4.tcpmaxsynbacklog = 262144
net.ipv4.tcptimestamps = 0
net.ipv4.tcpsynackretries = 1
net.ipv4.tcpsynretries = 1
net.ipv4.tcptwrecycle = 1
net.ipv4.tcptwreuse = 1
net.ipv4.tcpmem = 94500000 915000000 927000000
net.ipv4.tcpfintimeout = 1
net.ipv4.tcpkeepalivetime = 30
net.ipv4.iplocalportrange = 1024 65000
執行 sysctl -p 使內核修改生效
(10) 關於系統連接數的優化:
linux 默認值 open files 爲 1024
#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@www ~]# yum -y install libxml2-devel libcurl-devel openssl-devel bzip2-devel
安裝 libmcrypt
[root@www ~]# tar zxf libmcrypt-2.5.7.tar.gz
[root@wwwr ~]# cd libmcrypt-2.5.7/
[root@www libmcrypt-2.5.7]# ./configure --prefix=/usr/local/libmcrypt && make && make install
(2)編譯安裝 php
[root@www ~]# tar zxf php-5.6.27.tar.gz
[root@www ~]# cd php-5.6.27/
[root@www 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/libmcrypt
--with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --with-bz2
--enable-maintainer-zts
[root@www php-5.6.27]# make && make install
(3)提供 php 配置文件
[root@www php-5.6.27]# cp php.ini-production /etc /php.ini
(4)爲 php-fpm 提供腳本
[root@www php-5.6.27]# cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm
[root@www php-5.6.27]# chmod +x /etc/init.d/php-fpm
[root@www php-5.6.27]# chkconfig --add php-fpm
[root@www php-5.6.27]# chkconfig php-fpm on
(5)提供 php-fpm 配置文件並編輯:
#cp /usr/local/php5.6/etc/php-fpm.conf.default /usr/local/php5.6/etc/php-fpm.conf
[root@www ~]# vi /usr/local/php5.6/etc/php-fpm.conf
修改內容如下:
pid = run/php-fpm.pid
listen = 0.0.0.0:9000
pm.maxchildren = 50
pm.startservers = 5
pm.minspareservers = 5
pm.maxspareservers = 35
啓動 php-fpm 服務:
[root@www ~]# service php-fpm start
Starting php-fpm done
[root@www ~]# netstat -anpt | grep php-fpm
tcp 0 0 0.0.0.0:9000 0.0.0.0: LISTEN
25456/php-fpm: mast
[root@www ~]# firewall-cmd --permanent --add-port=9000/tcp
success
[root@www ~]# firewall-cmd --reload
Success
在 nginx.conf 文件的 server 中添加下面內容支持 php
location ~ ..(php|php5)?$ {
root html;
fastcgipass 127.0.0.1:9000;
fastcgiindex index.php;
include fastcgi.conf;
fastcgicache cachefastcgi;
fastcgicachevalid 200 302 1h;
fastcgicachevalid 301 1d;
fastcgicachevalid any 1m;
fastcgicacheminuses 1;
fastcgicacheusestale error timeout invalidheader http500;
fastcgicachekey http://$host$requesturi;
}
下面是 nginx.conf 的一個完整配置文件
user www www;
workerprocesses 4;
workercpuaffinity 0001 0010 0100 1000;
errorlog logs/error.log;
#errorlog logs/error.log notice;
#errorlog logs/error.log info;
pid logs/nginx.pid;
events {
use epoll;
workerconnections 65535;
multiaccept on;
}
http {
include mime.types;
defaulttype application/octet-stream;
#logformat main '$remoteaddr - $remoteuser [$timelocal] "$request" '
#'$status $bodybytessent "$httpreferer" '
#'"$httpuseragent" "$httpxforwardedfor"';
#accesslog logs/access.log main;
sendfile on;
tcpnopush on;
keepalivetimeout 65;
tcpnodelay on;
clientheaderbuffersize 4k;
openfilecache max=102400 inactive=20s;
openfilecachevalid 30s;
openfilecacheminuses 1;
clientheadertimeout 15;
clientbodytimeout 15;
resettimedoutconnection on;
sendtimeout 15;
servertokens off;
clientmaxbodysize 10m;
fastcgiconnecttimeout 600;
fastcgisendtimeout 600;
fastcgireadtimeout 600;
fastcgibuffersize 64k;
fastcgibuffers 4 64k;
fastcgibusybufferssize 128k;
fastcgitempfilewritesize 128k;
fastcgitemppath /usr/local/nginx1.10/nginxtmp;
fastcgiintercepterrors on;
fastcgicachepath /usr/local/nginx1.10/fastcgicache
keyszone=cachefastcgi:128m inactive=1d maxsize=10g;
gzip on;
gzipminlength 2k;
gzipbuffers 4 32k;

gziphttpversion 1.1;
gzipcomplevel 6;
gziptypes text/plain text/css text/javascript application/json application/javascript
application/x-javascript application/xml;
gzipvary on;
gzipproxied any;
server {
listen 80;
servername www.benet.com;
#charset koi8-r;
#accesslog logs/host.access.log main;
location ~ ^.+.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
validreferers none blocked www.benet.com benet.com;
if ($invalidreferer) {
#return 302 http://www.benet.com/img/nolink.jpg;
return 404;
break;
}
accesslog off;
}
location / {
root html;
index index.php index.html index.htm;
}
location ~ .(ico|jpe?g|gif|png|bmp|swf|flv)$ {
expires 30d;
#lognotfound off;
accesslog off;
}
location ~ .(js|css)$ {
expires 7d;
lognotfound off;
accesslog off;
}
location = /(favicon.ico|roboots.txt) {
accesslog off;
lognotfound off;
}
location /status {

stubstatus on;
}
location ~ ..(php|php5)?$ {
root html;
fastcgipass 127.0.0.1:9000;
fastcgiindex index.php;
include fastcgi.conf;
fastcgicache cachefastcgi;
fastcgicachevalid 200 302 1h;
fastcgicachevalid 301 1d;
fastcgicachevalid any 1m;
fastcgicacheminuses 1;
fastcgicacheusestale error timeout invalidheader http500;
fastcgicachekey http://$host$requesturi;
}
#errorpage 404 /404.html;
#redirect server error pages to the static page /50x.html

errorpage 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
重載 nginx 服務
[root@www ~]# /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&gt;
Nginx 站點的網頁目錄結如下
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

Nginx優化與防盜鏈

點擊頁面鏈接
Nginx優化與防盜鏈

從上圖可以看到防盜鏈設置生效了
(2)驗證 gzip 功能
使用谷歌瀏覽器測試訪問,如下圖顯示結果:(提示:在訪問測試頁之前按 F12 鍵)

Nginx優化與防盜鏈

用戶訪問 test.php文件,在上圖中 content-encoding:gzip表明響應給用戶的數據是壓縮傳輸。
(3)壓力測試
安裝 httpd-tools 軟件包
[root@www ~]# yum -y install httpd-tools
[root@www ~]# ab -c 500 -n 50000 http://www.benet.com/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 www.benet.com (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: www.benet.com
Server Port: 80
Document Path: /index.html
Document Length: 612 bytes
Concurrency Level: 500
Time taken for tests: 5.734 seconds
Complete requests: 50000
Failed requests: 0
Write errors: 0
Total transferred: 41800000 bytes
HTML transferred: 30600000 bytes
Requests per second: 8719.82 [#/sec] (mean)
Time per request: 57.341 [ms] (mean)
Time per request: 0.115 [ms] (mean, across all concurrent requests)
Transfer rate: 7118.92 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 1 25 4.2 25 38
Processing: 7 32 5.5 31 47
Waiting: 4 24 6.8 21 39
Total: 40 57 3.9 57 71
Percentage of the requests served within a certain time (ms)
50% 57
66% 59
75% 59
80% 60
90% 61
95% 62
98% 63
99% 64
100% 71 (longest request)
第二次壓力測試,比較兩次的差異
[root@www ~]# ab -c 1000 -n 100000 http://www.benet.com/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 www.benet.com (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: www.benet.com
Server Port: 80
Document Path: /index.html
Document Length: 612 bytes
Concurrency Level: 1000
Time taken for tests: 12.010 seconds
Complete requests: 100000
Failed requests: 0
Write errors: 0
Total transferred: 83600000 bytes
HTML transferred: 61200000 bytes
Requests per second: 8326.49 [#/sec] (mean)
Time per request: 120.099 [ms] (mean)
Time per request: 0.120 [ms] (mean, across all concurrent requests)
Transfer rate: 6797.80 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 1 53 8.9 53 82
Processing: 17 67 11.4 66 98
Waiting: 0 49 14.3 43 84
Total: 70 119 6.5 120 140
Percentage of the requests served within a certain time (ms)
50% 120
66% 122
75% 123
80% 124
90% 126
95% 128
98% 129
99% 130
100% 140 (longest request)
(5)xcache 加速 php
安裝 xcache
wget http://xcache.lighttpd.net/pub/Releases/3.2.0/xcache-3.2.0.tar.gz #下載
[root@www ~]# tar zxf xcache-3.2.0.tar.gz #解壓
[root@www ~]# cd xcache-3.2.0/ #進入安裝目錄
[root@www xcache-3.2.0]# /usr/local/php5.6/bin/phpize #用 phpize 生成 configure 配置文件
[root@www xcache-3.2.0]# ./configure --enable-xcache --enable-xcache-coverager
--enable-xcache-optimizer --with-php-config=/usr/local/php5.6/bin/php-config #配置
[root@www xcache-3.2.0]# make && make install #編譯、安裝
Installing shared extensions:
/usr/local/php5.6/lib/php/extensions/no-debug-zts-20131226/
安裝完成之後,出現下面的界面,記住以下路徑,後面會用到
/usr/local/php5.6/lib/php/extensions/no-debug-zts-20131226/
2) 創建 xcache 緩存文件
touch /tmp/xcache
chmod 777 /tmp/xcache
3) 拷貝 xcache 後臺管理程序到網站根目錄
[root@www 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-zts-20131226/xcache.so
[xcache.admin]
xcache.admin.enableauth = Off
[xcache]
xcache.shmscheme ="mmap"
xcache.size=60M
xcache.count =1
xcache.slots =8K
xcache.ttl=0
xcache.gcinterval =0
xcache.varsize=64M
xcache.varcount =1
xcache.varslots =8K
xcache.varttl=0
xcache.varmaxttl=0
xcache.vargcinterval =300
xcache.test =Off
xcache.readonlyprotection = Off
xcache.mmappath ="/tmp/xcache"
xcache.coredumpdirectory =""
xcache.cacher =On
xcache.stat=On
xcache.optimizer =Off
[xcache.coverager]
xcache.coverager =On
xcache.coveragedumpdirectory =""
測試
service php-fpm restart #重啓 php-fpm
瀏覽器打開網站根目錄下面的 xcache
http:// http://www.benet.com/xcache 可以看到如下頁面:
Nginx優化與防盜鏈

測試對 php 動態頁面的壓力測試
[root@www ~]# ab -c 1000 -n 100000 http://www.benet.com/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 www.benet.com (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: www.benet.com
Server Port: 80
Document Path: /test.php
Document Length: 85102 bytes
Concurrency Level: 1000
Time taken for tests: 13.686 seconds
Complete requests: 100000
Failed requests: 0
Write errors: 0
Total transferred: 8527900000 bytes
HTML transferred: 8510200000 bytes
Requests per second: 7306.71 [#/sec] (mean)
Time per request: 136.861 [ms] (mean)
Time per request: 0.137 [ms] (mean, across all concurrent requests)
Transfer rate: 608504.46 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 17 5.5 17 81
Processing: 21 119 10.8 121 140
Waiting: 1 17 6.7 16 68
Total: 50 136 8.1 137 151
Percentage of the requests served within a certain time (ms)
50% 137
66% 139
75% 140
80% 141
90% 143
95% 144
98% 146
99% 148
100% 151 (longest request)
*

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