nginx安全優化與性能優化

1.1 Nginx優化分類

安全優化(提升網站安全性配置)

性能優化(提升用戶訪問網站效率)

1.2 Nginx安全優化

1.2.1 隱藏nginx版本信息優化

官方配置參數說明:http://nginx.org/en/docs/http/ngx_http_core_module.html#server_tokens

官方參數:

Syntax: server_tokens on | off | build | string;    #後面這倆參數收費的

Default: server_tokens on;

Context: http, server, location

配置舉例:

[root@web01 ~]# cat /application/nginx/conf/nginx.conf

worker_processes 1;

events {

worker_connections 1024;

}

http {

include mime.types;

default_type application/octet-stream;

sendfile off;

keepalive_timeout 65;

log_format main '$remote_addr - $remote_user [$time_local] "$request" '

'$status $body_bytes_sent "$http_referer" '

'"$http_user_agent" "$http_x_forwarded_for"';

server {

listen 80;

server_name www.nmtui.com;

server_tokens off;

location / {

root html/www;

index index.html index.htm;

}

access_log logs/access_www.log main;

}

}

測試結果:

[root@web01 ~]# curl -I 10.0.0.8

HTTP/1.1 200 OK

Server: nginx

Date: Wed, 01 Nov 2017 18:32:40 GMT

Content-Type: text/html

Content-Length: 10

Last-Modified: Wed, 25 Oct 2017 01:20:56 GMT

Connection: keep-alive

ETag: "59efe6f8-a"

Accept-Ranges: bytes

1.2.2 修改nginx版本信息

修改版本信息需要修改程序源文件信息

修改內核信息

[root@web01 nginx-1.10.2]# vim src/core/nginx.h

# ···

13 #define NGINX_VERSION "6.6.6"                 #修改版本號

14 #define NGINX_VER "george/" NGINX_VERSION #web軟件名

22 #define NGINX_VAR "georgekai"              

# ···

修改頭部信息

[root@web01 nginx-1.10.2]# vim src/http/ngx_http_header_filter_module.c

# ···

49 static char ngx_http_server_string[] = "Server: george" CRLF;

# ···

修改錯誤頁顯示

[root@web01 nginx-1.10.2]# vim src/http/ngx_http_special_response.c

# ···

# 此處可以不修改

21 static u_char ngx_http_error_full_tail[] =

22 "<hr><center>" NGINX_VER "</center>" CRLF

23 "</body>" CRLF

24 "</html>" CRLF

25 ;

# ···

28 static u_char ngx_http_error_tail[] =

29 "<hr><center>kai</center>" CRLF

30 "</body>" CRLF

31 "</html>" CRLF

32 ;

# ···

修改完成後重新編譯

nginx -V                #查看之前的編譯參數

[root@web01 nginx-1.10.2]# ./configure --prefix=/application/nginx-1.10.2 --user=www --group=www --with-http_stub_status_module --with-http_ssl_module


make && make install            #make失敗查看下有沒有pcre-devel包

重啓服務

[root@web01 nginx-1.10.2]# /etc/init.d/nginx restart

訪問測試是否修改成功

[root@web01 ~]# curl -I blog.george.com

HTTP/1.1 200 OK

Server: george

Date: Wed, 01 Nov 2017 19:05:43 GMT

Content-Type: text/html

Content-Length: 10

Last-Modified: Wed, 25 Oct 2017 01:20:56 GMT

Connection: keep-alive

ETag: "59efe6f8-a"

Accept-Ranges: bytes

1.2.3 修改worker進程的用戶

第一種方法:利用編譯安裝配置參數,設定nginx默認worker進程用戶

useradd -s /sbin/nologin -M www

./configure --user=www --group=www

第二種方式:編寫nginx服務配置文件,設定nginx默認worker進程用戶

官方配置參數說明:http://nginx.org/en/docs/ngx_core_module.html#user

Syntax:user user [group];

Default: user nobody nobody;

Context: main

配置舉例:

[root@web02 conf]# cat nginx.conf

user www www; # 主區塊添加user參數

worker_processes 1;

events {

worker_connections 1024;

}

查看是否生效

[root@web01 nginx-1.10.2]# ps -ef|grep nginx

root 16987 1 0 15:14 ? 00:00:00 nginx: master process nginx

clsn 18484 16987 0 15:22 ? 00:00:00 nginx: worker process

root 18486 9593 0 15:22 pts/0 00:00:00 grep --color=auto nginx

1.2.4 上傳文件大小的限制(動態應用)

默認語法說明:

syntax:client_max_body_size size; #<==參數語法

default:client_max_body_size 1m; #<==默認值是1m

context:http,server,location #<==可以放置的標籤段

舉例配置:

http {

sendfile on;

keepalive_timeout 65;

client_max_body_size 1m; # 設置上傳文件最大值1M,還受博客程序限制

}

1.2.5 站點 Nginx站點目錄及文件URL訪問控制

   01. 根據目錄或擴展名,禁止用戶訪問指定數據信息

        避免用戶上傳一些腳本,惡意破會網站程序

location ~ ^/images/.*\.(php|php5|sh|pl|py|html)$

{

deny all;

}

location ~ ^/static/.*\.(php|php5|sh|pl|py)$

{

deny all;

}

location ~* ^/data/(attachment|avatar)/.*\.(php|php5)$

{

deny all;

}

   02. 當訪問禁止的數據信息時,進行頁面跳轉

Nginx下配置禁止訪問*.txt*.doc文件。

實際配置信息如下:

location ~* \.(txt|doc)$ {

if (-f $request_filename){

root /data/www/www;

#rewrite …..可以重定向到某個URL

break;

}

}

location ~* \.(txt|doc)${

root /data/www/www;

denyall;

}

   03. 根據IP地址或網絡進行訪問策略控制

location / {

deny 192.168.1.1;

allow 192.168.1.0/24;

allow 10.1.1.0/16;

deny all;

}

   04. 採用if判斷方式,進行訪問控制

if ($remote_addr = 10.0.0.7 ){

return 403;

}

1.2.6 配置Nginx,禁止非法域名解析訪問企業網站

作用:避免惡意用戶使用自己的域名也能解析到blog.george.com對應的IP上。

思路:只能通過域名訪問網站,IP不可以訪問。

第一種方式:配置一個server虛擬主機區塊,放置在所有server區塊最前面

server {

listen 80;

server_name - ;

return 501;

}


原理:首先域名解析爲IP,接下來是根據7層模型,經過2層MAC,在根據IP訪問到ngin服務器,IP如果符合了在根據4層端口匹配對應的server區塊,IP和端口都滿足了在根據5層域名匹配對應的server區塊,都不滿足,默認返回給第一個server區塊處理。

第二種方式:將計就計,通過你的域名訪問時候,自動跳轉到我的域名上

server {

listen 80 default_server;

server_name _;

rewrite ^(.*) http://www.nmtui.com/$1 permanent;

}



第三種方式:發現某域名惡意解析到公司的服務器IP,在server標籤裏添加以下代碼即可,若有多個server則要多處添加。

if ($host !~ ^www\.nmtui\.com$)

{

rewrite ^(.*) http://www.nmtui.com/$1 permanent;

}

1.2.7 Nginx圖片及目錄防盜鏈解決方案

   什麼是資源盜鏈 ?

   簡單地說,就是某些不法網站未經許可,通過在其自身網站程序裏非法調用其他網站的資源,然後在自己的網站上顯示這些調用的資源,達到填充自身網站的效果。

實現盜鏈過程:

01. 真正的合法網站(盜鏈的目標)  web01   www.nmtui.com www站點目錄有一個oldboy.jpg圖片

# 在站點目錄下,生成要被盜鏈的圖片信息

ls blog/oldboy.jpg

# 配置靜態虛擬主機 server {

listen 80;

server_name blog.george.com;

location / {

root html/blog;

index index.html index.htm;

}

# 確認生成盜鏈文件

   02. 不合法的網站(真正盜鏈網站)  www.daolian.com

# 編寫盜鏈網站配置文件

listen 80;

server_name blog.daolian.com;

location / {

root html/blog;

index index.html index.htm;

}

# 編寫一個html盜鏈文件

<html>

<head>

<title>george</title>

</head>

<body bgcolor=green>

george的博客!

<br>我的博客是

<a

href="http://blog.daolian.com" target="_blank">博客地址

</a>

<img src="http://blog.george.com/oldboy.jpg">        #盜取的圖片

</body>

</html>

    編寫盜鏈虛擬主機

server {

listen 80;

server_name blog.daolian.com;

location / {

root html;

index index.html index.htm;

}

}

         至此就實現了盜鏈。

03 常見防盜鏈解決方案的基本原理

1)     根據HTTP referer實現防盜鏈

    利用referer,並且針對擴展名rewrite重定向,下面的代碼爲利用referer且針對擴展名rewrite重定向,即實寫防盜鏈的Nginx配置。

# 在站點目錄下,生成要被盜鏈後要跳轉的圖片

ls blog/nolink.jpg         



         ~ .*\.

location ~* /\.(jpg|gif|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {  

root html/blog;

valid_referers none blocked *.george.com george.com;

if ($invalid_referer){

rewrite ^/ http://blog.george.com/nolink.png;

}

}

注:盜鏈網站盜取的是你的jpg圖片,上面被盜網站的location中匹配了jpg,但屬於valid_referers,所以會跳轉爲http://blog.george.com/nolink.png,也就實現了防盜鏈。

        如果rewrite跳轉的後的圖片也是jpg的圖片,那麼就造成無線循環.


但是這樣網站資源是實現了防盜,但是流量還是盜取的你的,所以使用下面的方法來實現將用戶提示的圖片到用戶本地緩存:

         設置expires的方法如下:在localtion加了緩存期限

[root@clsn www]# cat /application/nginx/conf/extra/www.conf server {

listen 80;

server_name www.nmtui.com;

root html/www;

index index.html index.htm;

access_log logs/www_access.log main;

#Preventing hot linking of images and other file types

location ~* ^.+\.(gif|jpg|swf|flv|rar|zip)$ {

valid_referers none blocked server_names *.nmtui.comnmtui.com;

if ($invalid_referer){

rewrite ^/ http://www.nmtui.com/img/nolink.png;

}

access_log off;                                    #在localtion加了緩存期限

root html/www;

expires 1d;

break;

}

}

注:none:正常的訪問 blocked:鎖定這些訪問

2) 根據cookie防盜鏈

3) 通過加密變換訪問路徑實現防盜鏈

    通過PHP代碼實現

    類似的可以研究下這個模塊:ngx_http_accesskey_module  nginx模塊

image.png

4) 在所有網站資源上添加水印或LOGO,讓盜鏈人員幫你做推廣宣傳

1.2.8 NGINX錯誤頁面優雅顯示

範例1:對錯誤代碼403實行本地頁面跳轉,命令如下:

###www server {

listen 80;

server_name www.nmtui.com;

location / {

root html/www;

index index.html index.htm;

}

error_page 403 /403.html; #<==當出現403錯誤時,會跳轉到403.html頁面

}

# 上面的/403.html是相對於站點根目錄html/www的。

範例250x頁面放到本地單獨目錄下,進行優雅顯示。

# redirect server error pages to the static page /50x.html

error_page 500 502 503 504 /50x.html;

location = /50x.html {

root /data0/www/html;

}

注:多個狀態碼可以在一行用空格分割

範例3:改變狀態碼爲新的狀態碼,並顯示指定的文件內容,命令如下:

error_page 404 =200 /empty.gif;


server {

listen 80;

server_name www.nmtui.com;

location / {

root /data0/www/bbs;

index index.html index.htm;

fastcgi_intercept_errors on;

error_page 404 =200 /ta.jpg;

access_log /app/logs/bbs_access.log commonlog;

}

}

範例4:錯誤狀態碼URL重定向,命令如下:

server {

listen 80;

server_name www.nmtui.com;

location / {

root html/www;

index index.html index.htm;

error_page 404 https://clsn.cnblogs.com;

#<==當出現404錯誤時,會跳轉到指定的URL https://clsn.cnblogs.com頁面顯示給用戶,這個URL一般是企業另外的可用地址

access_log /app/logs/bbs_access.log commonlog;

}

}


1.2.9 Nginx站點目錄文件及目錄權限優化

image.png

服務器角色

權限處理

安全係數

動態Web集羣

目錄權限755

文件權限644

所用的目錄,以及文件用戶和組都是root

環境爲Nginx+PHP   文件不能被改,目錄不能被寫入,安全係數10

static圖片集羣

目錄權限755

文件權限644

所用的目錄,以及文件用戶和組都是root

環境爲Nginx    文件不能被改,目錄不能被寫入,安全係數10

上傳upload集羣

目錄權限755

文件權限644

所用的目錄,以及文件用戶和組都是root

特別:用戶上傳的目錄設置爲755,用戶和組使用Nginx服務配置的用戶    

文件不能被改,目錄不能被寫入,但是用戶上傳的目錄允許寫入文件且需要通過Nginx的其他功能來禁止讀文件,安全係數8


1.2.10 Nginx防爬蟲優化

最簡單的方法:用wget 的某一個參數來實現爬蟲

                      

範例1:阻止下載協議代理,命令如下:

## Block download agents ##if ($http_user_agent ~* LWP::Simple|BBBike|wget)

{

return 403;

}

範例2:添加內容防止N多爬蟲代理訪問網站,命令如下:

這些爬蟲代理使用“|”分隔,具體要處理的爬蟲可以根據需求增加或減少,添加的內容如下

if ($http_user_agent ~* "qihoobot|Baiduspider|Googlebot|Googlebot-Mobile|Googlebot-Image|Mediapartners-Google|Adsbot-Google|Yahoo!Slurp China|YoudaoBot|Sosospider|Sogou spider|Sogou web spider|MSNBot"

{

return 403;

}


注:如果有新的爬蟲,需要查看nginx訪問日誌,來查詢,並添加到上面配置中

注:驗證碼也是防爬蟲的一種手段,12306的最難

1.2.11 利用Nginx限制HTTP的請求方法

#Only allow these request methods

#放在server區塊下

if ($request_method !~ ^(GET|HEAD|POST)$ ) {

return 501;

}


可以自己測試下限制GET:

if ($request_method ~ ^(GET)$ ) {

return 501;

}

#Do not accept DELETESEARCH and other methods

1.2.12 使用普通用戶啓動nginx

1、切換到普通用戶家目錄下,創建nginx所需文件

su - george

[nginx@web01 ~]$ mkdir -p blog/{conf,logs,html}

[nginx@web01 ~]$ cd blog/

[nginx@web01 blog]$ cp /application/nginx/conf/nginx.conf.default ./conf/

[nginx@web01 blog]$ grep -vE "^$|#" conf/nginx.conf.default > conf/nginx.conf

[nginx@web01 blog]$ cp /application/nginx/conf/mime.types conf/

2、編寫配置文件

[nginx@web01 ~]$ cat blog/conf/nginx.conf

worker_processes 4;

worker_cpu_affinity 0001 0010 0100 1000;

worker_rlimit_nofile 65535;

error_log /home/nginx/blog/logs/error.log;   #放到上面的nginx.conf中主區塊

user inca inca;

pid /home/nginx/blog/logs/nginx.pid;           #放到上面的ngixn.conf中主區塊

events {

use epoll;

worker_connections 1024;

}

http {

include mime.types;

default_type application/octet-stream;

sendfile on;

keepalive_timeout 65;

log_format main '$remote_addr - $remote_user [$time_local] "$request" '  

'$status $body_bytes_sent "$http_referer" '

'"$http_user_agent" "$http_x_forwarded_for"';    #也放到nginx.conf的http下

server {

listen 8080;                                      #普通用戶不能用知名端口 

server_name www.etiantian.org;

root /home/nginx/blog/html;

location / {

index index.html index.htm;

}

access_log /home/nginx/blog/logs/web_blog_access.log main; #放到nginx.conf

}

}

         注意:普通用戶不能使用知名端口,需要使用其他端口啓動服務

                    大於1024的端口可以讓普通用戶管理。

3、檢查配置文件語法,並啓動nginx服務

/application/nginx/sbin/nginx -t -c /home/nginx/blog/conf/nginx.conf

/application/nginx/sbin/nginx -c /home/nginx/blog/conf/nginx.conf &>/dev/null &

         注意:用戶也需要訪問8080,所以需要做一些跳轉方法:

          1.在負載均衡上做接收到用戶的請求拋的時候拋到8080

          2.防火牆NAT映射將8080映射爲80

1.3 Nginx性能優化

1.3.1 優化nginx worker進程個數

nginx服務主要有兩個重要進程:

 01) master進程:可以控制nginx服務的啓動 停止 或重啓

 02) worker進程:處理用戶請求信息,幫助用戶向後端服務進行請求(php mysql) 

  添加worker進程方法

vim nginx.conf

worker_processes 1; # 修改nginx配置文件中worker_processes指令後面的數值

  建議: 1. worker進程數量=等於CPU的核數 

               1.  worker進程數量=等於CPU的核數*2

如何在一個系統中獲悉CPU核心是多少?

①. 利用top命令--按數字1,獲取到CPU核數信息

②. grep processor /proc/cpuinfo|wc -l

③. lscpu

查看cpu核心數命令示例

示例一

[root@web01 ~]# top # 按數字1

top - 03:22:48 up 9 days, 26 min, 4 users, load average: 1.06, 0.99, 0.92

Tasks: 107 total, 1 running, 106 sleeping, 0 stopped, 0 zombie

Cpu0 : 0.2%us, 0.6%sy, 0.0%ni, 99.0%id, 0.1%wa, 0.0%hi, 0.0%si, 0.0%st

Cpu1 : 0.1%us, 0.1%sy, 0.0%ni, 99.1%id, 0.7%wa, 0.0%hi, 0.0%si, 0.0%st

Mem: 485984k total, 452536k used, 33448k free, 24984k buffers

Swap: 786428k total, 5912k used, 780516k free, 242048k cached

示例二

[root@web01 ~]# lscpu |grep CPU

CPU op-mode(s): 32-bit, 64-bit

CPU(s): 2

示例三

[root@web01 ~]# grep processor /proc/cpuinfo processor : 0

processor : 1

1.3.2 綁定不同的nginx進程到不同的CPU

4worker進程分配4核4路CPU資源方法:

worker_processes 4

worker_cpu_affinity 0001 0010 0100 1000;

8worker進程分配8核4路CPU資源方法;

worker_processes 8

worker_cpu_affinity 0001 0010 0100 1000 0001 0010 0100 1000; # 分配8進程方法

worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;

4worker進程分配4核2路CPU資源方法:

worker_processes 4

worker_cpu_affinity 0101 1010; # 將進程分配到兩顆CPU上

1.3.3 優化nginx事件處理模型

image.png

官方配置參數說明:http://nginx.org/en/docs/ngx_core_module.html#use

Syntax: use method;

Default: —

Context: events

關於事件處理模型可以參考:https://clsn.cnblogs.com/p/7750615.html#auto_id_10

舉例配置:

user www www;

worker_processes 1;

events {

worker_connections 1024;

use epoll; --- 指定使用的模型爲epoll

}

1.3.4 調整nginx單個進程允許的客戶端最大連接數

查看nginx進程當前的打開文件數

[root@clsn ~]# lsof -i:80

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME

nginx 10422 root 6u IPv4 11868856 0t0 TCP *:http (LISTEN)

nginx 10424 www 6u IPv4 11868856 0t0 TCP *:http (LISTEN)

nginx 10425 www 6u IPv4 11868856 0t0 TCP *:http

修改最大連接數方法

vim nginx.conf

events #<==events指令是設定Nginx的工作模式及連接數上限 {

worker_connections 1024

}

     worker_connections * worker_processes <= 系統最大打開文件數量

                此數值設置不要超過系統最大打開文件數量。

                ulimit -HSn                #查看系統最大打開文件數量

                ulimit -n 65535         #修改系統最大打開文件數量

1.3.5 配置Nginx worker進程最大打開文件數

舉例配置:

[root@web02 conf]# cat nginx.confuser www www;

worker_processes 1;

worker_rlimit_nofile 2048; # 設置worker進程打開文件數

1.3.6 優化nginx高效文件傳輸模式

sendfile參數的官方說明如下:

syntax:sendfile on | off; #<==參數語法

default:sendfile off; #<==參數默認大小

context:http,server,location,if in location #<==可以放置的標籤段

說明:在系統內核中,利用零拷貝方式實現數據傳輸

實現高效數據傳輸的兩種方式

第一種方式:tcp_nopush

syntax: tcp_nopush on | off; #<==參數語法

default: tcp_nopush off; #<==參數默認大小

context: http,server,location #<==可以放置的標籤段

說明:將數據包積攢到一定量時再進行傳輸

參數作用:

   激活或禁用Linux上的TCP_NODELAY選項。這個參數啓用只在連接傳輸進入到 keep-alive狀態。TCP_NODELAY和TCP_CORK基本上控制了包的"Nagle化",Nagle化在這裏 的含義是採用Nagle算法把較小的包組裝爲更大的幀。John Nagle是Nagle算法的發明人,後者就是用他的名字來命名的。

   此算法解決的問題就是所謂的silly window syndrome,中文稱"愚蠢窗口症候羣",具體含義是,因爲普遍終端應用程序每產生一次擊鍵操作就會發送一個包,很輕易地就能令網絡發生擁塞,Nagle化後來成了一種標準並且立即在因特網上得以實現。它現在已經成爲缺省配置了,但在我們看來,有些場合下希望發送小塊數據,把這一選項關掉也是合乎需要的。

 

第二種方式:tcp_nodelay

Syntax: tcp_nodelay on | off;

Default: tcp_nodelay on;

Context: http, server, location

說明:只要有數據包產生,不管大小多少,就儘快傳輸 

參數作用:

  激活或禁用Linux上的TCP_CORK socket選項,tcp_cork是linux下tcp/ip傳輸的一個標準了,這個標準的大概的意思是,一般情況下,在tcp交互的過程中,當應用程序接收到數據包後馬上傳送出去,不等待,而tcp_cork選項是數據包不會馬上傳送出去,等到數據包最大時,一次性的傳輸出去,這樣有助於解決網絡堵塞,已經是默認了。

  此選項僅僅當開啓sendfile時才生效, 激活這個.tcp_nopush參數可以允許把http response header和響應數據文件的開始部分放在一個文件裏發佈,其積極的作用是減少網絡報文段的數量。

強調:兩個指令是相悖的,請選擇其一開啓,不要同時開啓;

默認採用tcp_nodelay方式進行傳輸。

image.png

1.3.7 設置nginx服務超時參數

Nginx連接超時的參數設置

1) 設置參數: keepalive_timeout 60; # 長連接纔有意義 

keepalive_timeout參數的官方說明如下:

syntax:keepalive_timeout timeout [header_timeout];#<==參數語法

default:keepalive_timeout 75s;#<==參數默認大小

context:http,server,location #<==可以放置的標籤段

說明:客戶端和服務端都沒有數據傳輸時,進行超時時間倒計時,一旦超時時間讀取完畢還沒有數據傳輸,就斷開連接

2) 設置參數:client_header_timeout 55;

syntax:client_header_timeout time; #<==參數語法

default:client_header_timeout 60s; #<==參數默認大小

context:http,server #<==可以放置的標籤段

說明:表示定義客戶端請求報文發送的間隔超時時間,客戶端發送的請求報文中請求頭信息的間隔時間

3)設置參數:client_body_timeout 55;

syntax:client_body_timeout time; #<==參數語法

default:client_body_timeout 60s; #<==默認值是60秒

context:http,server,location #<==可以放置的標籤段

說明:表示定義服務端響應報文發送的間隔超時時間,客戶端發送的請求報文中請求主體信息的間隔時間

4)設置參數:send_timeout 60s

syntax:send_timeout time; #<==參數語法

default:send_timeout 60s; #<==默認值是60秒

context:http,server,location #<==可以放置的標籤段

說明:表示定義客戶端讀取服務端響應報文的間隔超時時間,服務端發送的響應報文間隔時間

1.3.8 配置Nginx gzip壓縮實現性能優化

1.     Nginx gzip壓縮功能介紹

Nginx gzip壓縮模塊提供了壓縮文件內容的功能,用戶請求的內容在發送到用戶客戶端之前, Nginx服務器會根據一些具體的策略實施壓縮,以節約網站出口帶寬,同時加快數據傳輸效率,來提升用戶訪問體驗。

2.     Nginx gzip壓縮的優點

提升網站用戶體驗:

  發送給用戶的內容小了,用戶訪問單位大小的頁面就加快了,用戶體驗提升了,網站口碑就好了。

 節約網站帶寬成本:

   數據是壓縮傳輸的,因此節省了網站的帶寬流量成本,不過壓縮時會稍 微消耗一些CPU資源,這個一般可以忽略。

此功能既能提升用戶體驗,又能使公司少花錢,一舉多得。對於幾乎所有的Web服務來說,這 是一個非常重要的功能,Apache服務也有此功能。

官方用法參考鏈接:http://nginx.org/en/docs/http/ngx_http_gzip_module.html#gzip

gzip on;

gzip_min_length 1k;

gzip_buffers 4 16k;

gzip_http_version 1.1;

gzip_comp_level 4;

gzip_types text/css text/xml application/javascript;

gzip_vary on;

說明:將服務端響應的數據信息進行壓縮,可以有效節省帶寬,提高用戶訪問效率

            gzip_type 可參考mime.conf媒體資源類型選擇壓縮類型。

需要和不需要壓縮的對象

  1. 純文本內容壓縮比很高,因此,純文本的內容最好進行壓縮,例如:html、js、css、xml、shtml等格式的文件。

  2. 被壓縮的純文本文件必須要大於1KB,由於壓縮算法的特殊原因,極小的文件壓縮後可能反而變大。

  3. 圖片、視頻(流媒體)等文件儘量不要壓縮,因爲這些文件大多都是經過壓縮的。

  4. 如果再壓縮很可能不會減小或減小很少,或者有可能增大,同時壓縮時還會消耗大量的CPU、內存資源。

壓縮配置參數說明

gzip on ;

#<==開啓gzip壓縮功能。

gzip_min_length lk;

#<==設置允許壓縮的頁面最小宇節數,頁面宇節數從header頭的Content-Length中獲取。默認值是0,表示不管頁面多大都進行壓縮。建議設置成大於1K,如果小於1K可能會越壓越大。

gzip_buffers 4 16k;

#<==壓縮緩衝區大小。表示申請4個單位爲16K的內存作爲s壓縮結果流緩存,默認值是申請與原始數據大小相同的內存空間來存儲gzip壓縮結果。

gzip_http_version 1.1 ;

#<==壓縮版本(默認1.1,前端爲squid2.5時使用1.0),用於設置識別HTTP協議版本,默認是1.1, 目前大部分瀏覽器已經支持GZIP解壓,使用默認即可。 用什麼版本壓縮的,用什麼版本解壓。

gzip_comp_level 2 ;

#<==壓縮比率。用來指定gzip壓縮比,1壓縮比最小,處理速度最快;9壓縮比最大,傳輸速度快,但處理最慢,也比較消耗CPU資源。

gzip_types text/plain application/x-javascript text/css application/xml ;

#<==用來指定壓縮的類型,"text/html"類型總是會被壓縮,這個就是HTTP原理部分講的媒體類型。

gzip_vary on ;

#<==vary header支持。該選項可以讓前端的緩存服務器緩存經過gzip壓縮的頁面,例如用Squid緩存 經過Nginx壓縮的數據。

1.3.9 配置Nginx expires緩存實現性能優化

簡單地說,Nginx expires的功能就是爲用戶訪問的網站內容設定一個過期時間,當用戶第一次訪問這些內容時,會把這些內容存儲在用戶瀏覽器本地,這樣用戶第二次及以後繼續訪問該網站時,瀏覽器會檢查加載已經緩存在用戶瀏覽器本地的內容,就不會去服務器下載了,直到緩存的內容過期或被清除爲止。

Nginx expires功能優點

  1. expires可以降低網站的帶寬,節約成本。

  2. 加快用戶訪問網站的速度,提升用戶訪問體驗。

  3. 服務器訪問量降低了,服務器壓力就減輕了,服務器成本也會降低,甚至可以節約人力成本。

  4. 對於幾乎所有的Web服務來說,這是非常重要的功能之一,Apache服務也有此功能。

image.png

實踐配置

[root@web02 extra]# cat blog.conf server {

listen 80;

server_name blog.etiantian.org;

server_tokens off;

# 靜態請求處理的location

location / {

root html/blog;

index index.php index.html index.htm;

}

# 動態請求處理的location

location ~* .*\.(php|php5)?$ {

root html/blog;

fastcgi_pass 127.0.0.1:9000;

fastcgi_index index.php;

include fastcgi.conf;

}

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$

{

expires 10y;

root html/blog;

}

location ~ .*\.(js|css)$

{

expires 30d;

root html/blog;

}

}

location / {

expires 3650d;

}

注意事項:

   01. 進行緩存的時間要設置合理

   02. 不是所有請求的數據信息都可以進行緩存

   萬一緩存錯誤,將相應緩存的數據信息名稱進行更改(在服務器端站點目錄下進行更改)


企業網站有可能不希望被緩存的內容

  1. 廣告圖片,用於廣告服務,都緩存了就不好控制展示了。

  2. 網站流量統計工具(JS代碼),都緩存了流量統計就不準了。

  3. 更新很頻繁的文件(google的logo),這個如果按天,緩存效果還是顯著的。



1.3.10 配置FastCGI優化

FastCGI Cache資料見:

http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_cache

FastCGI常見參數的Nginx配置示例如下:

[root@nginx conf]# cat nginx.conf

worker_processes 4;

worker_cpu_affinity 0001 0010 0100 1000;

worker_rlimit_nofile 65535;

user nginx;

events {

use epoll;

worker_connections 10240;

}

http {

include mime.types;

default_type application/octet-stream;

sendfile on;

tcp_nopush on;

keepalive_timeout 65;

tcp_nodelay on;

client_header_timeout 15;

client_body_timeout 15;

send_timeout 15;

log_format main '$remote_addr - $remote_user [$time_local] "$request" '

'$status $body_bytes_sent "$http_referer" '

'"$http_user_agent" "$http_x_forwarded_for"';

server_tokens off;

fastcgi_connect_timeout 240;

fastcgi_send_timeout 240;

fastcgi_read_timeout 240;

fastcgi_buffer_size 64k;

fastcgi_buffers 4 64k;

fastcgi_busy_buffers_size 128k;

fastcgi_temp_file_write_size 128k;

#fastcgi_temp_path /data/ngx_fcgi_tmp;

fastcgi_cache_path /data/ngx_fcgi_cache levels=2:2 keys_zone=ngx_fcgi_cache:512m inactive=1d max_size=40g;

#web............... server {

listen 80;

server_name blog.nmtui.com;

root html/blog;

location / {

root html/blog;

index index.php index.html index.htm;

}

location ~ .*\.(php|php5)${

fastcgi_pass 127.0.0.1:9000;

fastcgi_index index.php;

include fastcgi.conf;

fastcgi_cache ngx_fcgi_cache;

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 error timeout invalid_header http_500;

fastcgi_cache_key http://$host$request_uri;

}

access_log logs/web_blog_access.log main;

}

upstream blog_etiantian{

server 10.0.0.8:8000 weight=1;

}

server {

listen 8000;

server_name blog.nmtui.com;

location / {

proxy_pass http://blog_etiantian;

proxy_set_header Host $host;

proxy_set_header X-Forwarded-For $remote_addr;

}

access_log logs/proxy_blog_access.log main;

}

}

FastCGI常見參數列表說明:

Nginx FastCGI 相關參數

說明

fastcgi_connect_timeout

表示nginx服務器和後端FastCGI服務器連接的超時時間,默認值爲60秒,這個參數值通常不要超過75秒,因爲建立的連接越多,消耗的資源就越多

fastcgi_send_timeout

設置nginx傳輸請求到FastCGI服務器的超時時間,這個超時時間不是整個請求的超時時間,而是兩個成功請求的之間間隔時間爲超時時間,如果這個時間內,FastCGI服務沒有收到任何信息,連接將關閉

fastcgi_read_timeout

設置nginxFastCGI服務器讀取響應信息的超時時間苯示連捿建立成功後, nginx等待後端服務器的響應時間,是nginx進入後端的排隊之中的等候處理的時間,實際上是讀取FastCGI響應成功信息的間隔時間,

fastcgi_buffer_size

這是Nginx FastCGI的緩衝區大小參數,設定用來讀取從FastCGI服務器端收到的第一部分響應信息的緩衝區大小,這裏的第一部分通常會包含一個小的響應頭部s默認情況下,這個參數的大小等價於_個內存頁。不是4k就是8k 根據相應系統平臺來決定,也可以更小。

fastcgi_buffers

設定用來讀取從FastCGI服務器端收到的響應信息的緩衝區大小和緩衝區數是,默認值爲fastcgi_buffer 8 4k|8k;

指定本地需要用多少和多大的緩衝區來緩衝FastCGI的應答請求,如果一個 PHP腳本產生的頁面大小爲256KB ,那麼會爲其分配464KB的緩衝區來緩存;如果頁面大小大於256KB ,那麼大於256KB的部分會緩存到fastcgi_temp 指定的路徑中,但是這並不是好方法,因爲內存中的數據處理速度要快於硬盤。一般這個值應該爲站點中PHP腳本產生的頁面大小的中間值,如果站點大部分腳本所產生的頁面大小爲256KB ,那麼可以把這個值設置爲"16 16k" , "4 64k"

fastcgi_busy_buffers_size

用於設置系統很忙時可以使用的fastcgi_buffers大小,言方推薦的大小爲fastcgi_buffers*2 ;默認值爲fastcgi_busy_buffers_size 8k|16k

fastcgi_temp_file_write_size

FastCGI臨時文件的大小,可以設置爲128~256KB ; 默認fastcgi_temp_file_write_size 8k|16k;

fastcgi_cache oldboy_nginx

表示開後FastCGI緩存併爲其指定一個名稱。開後緩存非常有用,可以有效降CPU的負載,並且防止502錯誤的發生,但是開後緩存也可能引起其它問題,要根據具體情況來選擇

fastcgi_cache_path

實例:fastcgi_cache_path /data/nginx/cache levels = 2:2 keys_zone = ngx_fcgi_cache:512m inactive = ld max_size=40g; fastcgi_cache緩存目錄,可以設置目錄前列層級,比如2:2會生成256*256 個子目錄,keys_zone是這個緩存空間的名字,cache是用多少內存(這樣熱門的內容,nginx會直接放入內存,提高訪問速度)。inactive表示默認失效時間,max_size表示最多用多少硬盤空間,雲要注意的是fastcgi_cache緩存是先寫在fastcgi_temp_path在移到fastcgi_cache_path中去的,所以這個兩個目錄最好在同一個分區,從0.8.9之後可以在不同的分區,不過還是建議放在_分區。

fastcgi_cache_valid

示例:fastcgi_cache_valid 200 302 lh; 

用來指定應答代碼的緩存時間,實例中的值表示將200302應答緩存1個小時; 

示例:fastcgi_cache_valid 301 Id; 

301應答緩存1天;

fastcgi_cache_min_uses

示例:fastcgi_cache_min_uses 1;  設置清求幾次之後晌應將被緩存,1表示一次即被緩存

fastcgi_cache_use_stale

示例:fastcgi_cache_use_stale error timeout invalid_header http_500 定義在哪些情況下使用過期緩存

fastcgi_cache_key

示例:fastcgi_cache_key requestmethod://requestmethod://hostrequesturi;fastcgi.cache.keyhttp://requesturi;fastcgi.cache.keyhttp://host$request_uri;

定義fastcgi_cachekey ,示例中以請求的URI作爲緩存的keynginx會取這個keymd5作爲緩存文件,如果設置了緩存散列目錄,nginx會從後往前取梠應的位數作爲目錄。注意一定要加作爲cache key,否則如果先請求的爲head 類型,後面的GET清求返回爲空。

1.4 日誌方面優化

1.4.1 配置Nginx服務相關日誌操作

01. 進行日誌的切割

[root@clsn ~]# mkdir /server/scripts/ -p

[root@clsn ~]# cd /server/scripts/

[root@clsn scripts]# vim cut_nginx_log.sh

#!/bin/bash

cd /application/nginx/logs &&\

/bin/mv www_access.log www_access_$(date +%F -d -1day).log #<==將日誌按日期改成前一天的名稱

/application/nginx/sbin/nginx -s reload #<==重新加載nginx使得觸發重新生成訪問日誌文件

提示:實際上腳本的功能很簡單,就是改名日誌,然後加載nginx,重新生成文件記錄日誌

說明:也可以編輯使用logrotate日誌切割服務,進行日誌切割

02. 進行日誌的選擇記錄

如:進行訪問的圖片都不記錄到日誌

location ~ .*\.(js|jpg|JPG|jpeg|JPEG|css|bmp|gif|GIF)$ {

access_log off;

}

03. 進行日誌文件授權

假如日誌目錄爲/app/logs,則授權方法如下:

chown -R root.root /app/logs

chmod -R 700 /app/logs

04.進程日誌清理

使用定時任務定時清除沒用的日誌

05. 日誌信息儘量彙總備份

[root@clsn ~]# zgrep 456 clsn.tar.gz

1.4.2 查看軟件編譯時的參數

. 查看nginx安裝時編譯了哪些參數

/application/nginx/sbin/nginx -V

. 查看apache安裝時編譯了哪些參數

cat /application/apache/build/config.nice

/application/apache/bin/apachectl -V #<--也可查看安裝時編譯信息,但顯示的不全

. 查看mysql安裝時編譯了哪些參數

grep CONFIGURE_LINE /application/mysql/bin/mysqlbug

PSmysql二進制包的安裝方式,是無法看到編譯參數的,默認爲空

. 查看php安裝時編譯了哪些參數

/application/php/bin/php -i|grep configure


小夥伴們可以關注我的公衆號:linux運維菜鳥之旅,閱讀更方便!

qrcode_for_gh_5ecc48d3d14a_258.jpg



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