1. 程式人生 > >Nginx配置檔案詳解

Nginx配置檔案詳解

Nginx是一款面向效能設計的HTTP伺服器,相較於Apache、lighttpd具有佔有記憶體少,穩定性高等優勢。

#nginx程序,一般設定為和cpu核數一樣
worker_processes 4;                        
#錯誤日誌存放目錄 
error_log  /data1/logs/error.log  crit;  
#執行使用者,預設即是nginx,可不設定
user nginx       
#程序pid存放位置
pid        /application/nginx/nginx.pid;        

#Specifies the value for maximum file descriptors that can be opened by this process. 
#最大檔案開啟數(連線),可設定為系統優化後的ulimit -HSn的結果
worker_rlimit_nofile 51200;

cpu親和力配置,讓不同的程序使用不同的cpu

worker_cpu_affinity 0001 0010 0100 1000 0001 00100100 1000;

#工作模式及連線數上限
events 
{
  use epoll;       #epoll是多路複用IO(I/O Multiplexing)中的一種方式,但是僅用於linux2.6以上核心,可以大大提高nginx的效能
  worker_connections 1024;  #;單個後臺worker process程序的最大併發連結數
}
###################################################
http 
{

include mime.types; #副檔名與型別對映表
default_type application/octet-stream; #預設檔案型別

#limit模組,可防範一定量的DDOS攻擊
#用來儲存session會話的狀態,如下是為session分配一個名為one的10M的記憶體儲存區,限制了每秒只接受一個ip的一次請求 1r/s
  limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
  limit_conn_zone $binary_remote_addr zone=addr:10m;
  include       mime.types;
  default_type  application/octet-stream;

#第三方模組lua防火牆
    lua_need_request_body on;
    #lua_shared_dict limit 50m;
    lua_package_path "/application/nginx/conf/waf/?.lua";
    init_by_lua_file "/application/nginx/conf/waf/init.lua";
    access_by_lua_file "/application/nginx/conf/waf/access.lua";

 #設定請求快取    
  server_names_hash_bucket_size 128;
  client_header_buffer_size 512k;
  large_client_header_buffers 4 512k;
  client_max_body_size 100m;


  #隱藏響應header和錯誤通知中的版本號
  server_tokens off;
  #開啟高效傳輸模式   
  sendfile on;

-------------------------------------------------------------------------------------------------
  #啟用tcp_nopush引數可以允許把httpresponse header和檔案的開始放在一個檔案裡釋出,
  積極的作用是減少網路報文段的數量
  tcp_nopush     on;
  #啟用tcp_nodelay,核心會等待將更多的位元組組成一個數據包,從而提高I/O效能
  tcp_nodelay on;

tcp_nopush

複製程式碼

官方:

tcp_nopush

Syntax: tcp_nopush on | off

Default: off

Context: http

server

location

Reference: tcp_nopush

This directive permits or forbids the use of thesocket options TCP_NOPUSH on FreeBSD or TCP_CORK on Linux. This option is onlyavailable when using sendfile.

Setting this option causes nginx to attempt to sendit’s HTTP response headers in one packet on Linux and FreeBSD 4.x

You can read more about the TCP_NOPUSH and TCP_CORKsocket options here.

linux 下是tcp_cork,上面的意思就是說,當使用sendfile函式時,tcp_nopush才起作用,它和指令tcp_nodelay是互斥的。tcp_cork是linux下tcp/ip傳輸的一個標準了,這個標準的大概的意思是,一般情況下,在tcp互動的過程中,當應用程式接收到資料包後馬上傳送出去,不等待,而tcp_cork選項是資料包不會馬上傳送出去,等到資料包最大時,一次性的傳輸出去,這樣有助於解決網路堵塞,已經是默認了。

也就是說tcp_nopush = on 會設定呼叫tcp_cork方法,這個也是預設的,結果就是資料包不會馬上傳送出去,等到資料包最大時,一次性的傳輸出去,這樣有助於解決網路堵塞。

以快遞投遞舉例說明一下(以下是我的理解,也許是不正確的),當快遞東西時,快遞員收到一個包裹,馬上投遞,這樣保證了即時性,但是會耗費大量的人力物力,在網路上表現就是會引起網路堵塞,而當快遞收到一個包裹,把包裹放到集散地,等一定數量後統一投遞,這樣就是tcp_cork的選項乾的事情,這樣的話,會最大化的利用網路資源,雖然有一點點延遲。

對於nginx配置檔案中的tcp_nopush,預設就是tcp_nopush,不需要特別指定,這個選項對於www,ftp等大檔案很有幫助

複製程式碼

tcp_nodelay

複製程式碼

TCP_NODELAY和TCP_CORK基本上控制了包的“Nagle化”,Nagle化在這裡的含義是採用Nagle演算法把較小的包組裝為更大的幀。 John Nagle是Nagle演算法的發明人,後者就是用他的名字來命名的,他在1984年首次用這種方法來嘗試解決福特汽車公司的網路擁塞問題(欲瞭解詳情請參看IETF RFC 896)。他解決的問題就是所謂的silly window syndrome,中文稱“愚蠢視窗症候群”,具體含義是,因為普遍終端應用程式每產生一次擊鍵操作就會發送一個包,而典型情況下一個包會擁有一個位元組的資料載荷以及40個位元組長的包頭,於是產生4000%的過載,很輕易地就能令網路發生擁塞,。 Nagle化後來成了一種標準並且立即在因特網上得以實現。它現在已經成為預設配置了,但在我們看來,有些場合下把這一選項關掉也是合乎需要的。

       現在讓我們假設某個應用程式發出了一個請求,希望傳送小塊資料。我們可以選擇立即傳送資料或者等待產生更多的資料然後再一次傳送兩種策略。如果我們馬上傳送資料,那麼互動性的以及客戶/伺服器型的應用程式將極大地受益。如果請求立即發出那麼響應時間也會快一些。以上操作可以通過設定套接字的TCP_NODELAY = on 選項來完成,這樣就禁用了Nagle 演算法。

       另外一種情況則需要我們等到資料量達到最大時才通過網路一次傳送全部資料,這種資料傳輸方式有益於大量資料的通訊效能,典型的應用就是檔案伺服器。應用 Nagle演算法在這種情況下就會產生問題。但是,如果你正在傳送大量資料,你可以設定TCP_CORK選項禁用Nagle化,其方式正好同 TCP_NODELAY相反(TCP_CORK和 TCP_NODELAY是互相排斥的)。

複製程式碼

-------------------------------------------------------------------------------------
 #FastCGI相關引數:為了改善網站效能:減少資源佔用,提高訪問速度

fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;

----------------------------------------------

#連線超時時間,單位是秒
  keepalive_timeout 60;

  #開啟gzip壓縮功能
    gzip on;
 #設定允許壓縮的頁面最小位元組數,頁面位元組數從header頭的Content-Length中獲取。預設值是0,表示不管頁面多大都進行壓縮。建議設定成大於1K。如果小於1K可能會越壓越大。
  gzip_min_length  1k;

#壓縮緩衝區大小。表示申請4個單位為16K的記憶體作為壓縮結果流快取,預設值是申請與原始資料大小相同的記憶體空間來儲存gzip壓縮結果。
  gzip_buffers     4 16k;

#壓縮版本(預設1.1,前端為squid2.5時使用1.0)用於設定識別HTTP協議版本,預設是1.1,目前大部分瀏覽器已經支援GZIP解壓,使用預設即可。
  gzip_http_version 1.0;

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

#用來指定壓縮的型別,“text/html”型別總是會被壓縮
  gzip_types       text/plain application/x-javascript text/css application/xml;
  #vary header支援。該選項可以讓前端的快取伺服器快取經過GZIP壓縮的頁面,例如用

Squid快取經過Nginx壓縮的資料。

gzip_vary off;
#開啟ssi支援,預設是off
  ssi on;
  ssi_silent_errors on;
#設定日誌模式
    log_format  access  '$remote_addr - $remote_user [$time_local] "$request" '
                        '$status $body_bytes_sent "$http_referer" '
                        '"$http_user_agent" $http_x_forwarded_for';

#反向代理負載均衡設定部分

#upstream表示負載伺服器池,定義名字為backend_server的伺服器池
upstream backend_server {
    server   10.254.244.20:81 weight=1 max_fails=2 fail_timeout=30s;
    server   10.254.242.40:81 weight=1 max_fails=2 fail_timeout=30s;
    server   10.254.245.19:81 weight=1 max_fails=2 fail_timeout=30s;
    server   10.254.243.39:81 weight=1 max_fails=2 fail_timeout=30s;
  #設定由 fail_timeout 定義的時間段內連線該主機的失敗次數,以此來斷定 fail_timeout 定義的時間段內該主機是否可用。預設情況下這個數值設定為 1。零值的話禁用這個數量的嘗試。

設定在指定時間內連線到主機的失敗次數,超過該次數該主機被認為不可用。

#這裡是在30s內嘗試2次失敗即認為主機不可用!
  }
###################

#基於域名的虛擬主機
  server
  {

#監聽埠
    listen       80;
    server_name  www.abc.com abc.com;    
    index index.html index.htm index.php;    #首頁排序
    root  /data0/abc;                            #站點根目錄,即網站程式存放目錄 
    error_page 500 502 404 /templates/kumi/phpcms/404.html;   #錯誤頁面
#偽靜態   將www.abc.com/list....html的檔案轉發到index.php。。。
#rewrite ^/list-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /index.php?m=content&c=index&a=lists&catid=$1&types=$2&country=$3&language=$4&age=$5&startDate=$6&typeLetter=$7&type=$8&page=$9 last;
#location 標籤,根目錄下的.svn目錄禁止訪問
    location ~ /.svn/ {
     deny all;
    }
            location ~ \.php$   
             {  #符合php副檔名的請求排程到fcgi server  
              fastcgi_pass  127.0.0.1:9000;  #拋給本機的9000埠
              fastcgi_index index.php;    #設定動態首頁
              include fcgi.conf;
             }
            allow   219.237.222.30 ;  #允許訪問的ip
            allow   219.237.222.31 ;
            allow   219.237.222.32 ;
            allow   219.237.222.33 ;
            allow   219.237.222.34 ;
            allow   219.237.222.35 ;
            allow   219.237.222.61 ;
            allow   219.237.222.28 ;
            deny    all;            #禁止其他ip訪問
            }
    location ~ ^/admin.php
         {
            location ~ \.php$
             {
              fastcgi_pass  127.0.0.1:9000;
              fastcgi_index index.php;
              include fcgi.conf;
             }
            allow   219.237.222.30 ;
            allow   219.237.222.31 ;
            allow   219.237.222.32 ;
            allow   219.237.222.33 ;
            allow   219.237.222.34 ;
            allow   219.237.222.35 ;
            allow   219.237.222.61;
            allow   219.237.222.28;
         deny    all;
            }

#將符合js,css檔案的等設定expries快取引數,要求瀏覽器快取。

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

       expires      30d; #客戶端快取上述js,css資料30天

    }

##add by 20140321#######nginx防sql注入##########

###start####
if ( $query_string ~* ".*[\;'\<\>].*" ){
    return 444;
    }
if ($query_string  ~* ".*(insert|select|delete|update|count|\*|%|master|truncate|declare|\'|\;|and|or|\(|\)|exec).* ") 
    {  
    return 444; 
    }
if ($request_uri ~* "(cost\()|(concat\()") {
                 return 444;
    }
if ($request_uri ~* "[+|(%20)]union[+|(%20)]") {
                 return 444;
    }
if ($request_uri ~* "[+|(%20)]and[+|(%20)]") {
                 return 444;
    }
if ($request_uri ~* "[+|(%20)]select[+|(%20)]") {
                 return 444;
    }
set $block_file_injections 0;
if ($query_string ~ "[a-zA-Z0-9_]=(\.\.//?)+") {
set $block_file_injections 1;
}
if ($query_string ~ "[a-zA-Z0-9_]=/([a-z0-9_.]//?)+") {
set $block_file_injections 1;
}
if ($block_file_injections = 1) {
return 448;
}
set $block_common_exploits 0;
if ($query_string ~ "(<|%3C).*script.*(>|%3E)") {
set $block_common_exploits 1;
}
if ($query_string ~ "GLOBALS(=|\[|\%[0-9A-Z]{0,2})") {
set $block_common_exploits 1;
}
if ($query_string ~ "_REQUEST(=|\[|\%[0-9A-Z]{0,2})") {
set $block_common_exploits 1;
}
if ($query_string ~ "proc/self/environ") {
set $block_common_exploits 1;
}
if ($query_string ~ "mosConfig_[a-zA-Z_]{1,21}(=|\%3D)") {
set $block_common_exploits 1;
}
if ($query_string ~ "base64_(en|de)code\(.*\)") {
set $block_common_exploits 1;
}
if ($block_common_exploits = 1) {
return 444;
}
set $block_spam 0;
if ($query_string ~ "\b(ultram|unicauca|valium|viagra|vicodin|xanax|ypxaieo)\b") {
set $block_spam 1;
}
if ($query_string ~ "\b(erections|hoodia|huronriveracres|impotence|levitra|libido)\b") {
set $block_spam 1;
}
if ($query_string ~ "\b(ambien|blue\spill|cialis|cocaine|ejaculation|erectile)\b") {
set $block_spam 1;
}
if ($query_string ~ "\b(lipitor|phentermin|pro[sz]ac|sandyauer|tramadol|troyhamby)\b") {
set $block_spam 1;
}
if ($block_spam = 1) {
return 444;
}
set $block_user_agents 0;
if ($http_user_agent ~ "Wget") {
 set $block_user_agents 1;
}
# Disable Akeeba Remote Control 2.5 and earlier
if ($http_user_agent ~ "Indy Library") {
set $block_user_agents 1;
}
# Common bandwidth hoggers and hacking tools.
if ($http_user_agent ~ "libwww-perl") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "GetRight") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "GetWeb!") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "Go!Zilla") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "Download Demon") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "Go-Ahead-Got-It") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "TurnitinBot") {
set $block_user_agents 1;
}
if ($http_user_agent ~ "GrabNet") {
set $block_user_agents 1;
}
if ($block_user_agents = 1) {
return 444;
}

###end####
     location ~ ^/list {
         #如果後端的伺服器返回502、504、執行超時等錯誤,自動將請求轉發到upstream負載均衡池中的另一臺伺服器,實現故障轉移。
         proxy_next_upstream http_502 http_504 error timeout invalid_header;
         proxy_cache cache_one;
         #對不同的HTTP狀態碼設定不同的快取時間
         proxy_cache_valid  200 301 302 304 1d;
         #proxy_cache_valid  any 1d;
         #以域名、URI、引數組合成Web快取的Key值,Nginx根據Key值雜湊,儲存快取內容到二級快取目錄內
         proxy_cache_key $host$uri$is_args$args;
         proxy_set_header Host  $host;
         proxy_set_header X-Forwarded-For  $remote_addr;
         proxy_ignore_headers "Cache-Control" "Expires" "Set-Cookie";
         #proxy_ignore_headers Set-Cookie;
         #proxy_hide_header Set-Cookie;
         proxy_pass http://backend_server;
         add_header      Nginx-Cache     "$upstream_cache_status  from  km";

          expires      1d;
        }

    access_log  /data1/logs/abc.com.log access;    #nginx訪問日誌
  }
-----------------------ssl(https)相關------------------------------------

server {
  listen 13820; #監聽埠
  server_name localhost;
  charset utf-8; #gbk,utf-8,gb2312,gb18030 可以實現多種編碼識別
  ssl on; #開啟ssl
  ssl_certificate /ls/app/nginx/conf/mgmtxiangqiankeys/server.crt; #服務的證書
  ssl_certificate_key /ls/app/nginx/conf/mgmtxiangqiankeys/server.key; #服務端key
  ssl_client_certificate /ls/app/nginx/conf/mgmtxiangqiankeys/ca.crt; #客戶端證書
  ssl_session_timeout 5m; #session超時時間
  ssl_verify_client on; # 開戶客戶端證書驗證 
  ssl_protocols SSLv2 SSLv3 TLSv1; #允許SSL協議 
  ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; #加密演算法
  ssl_prefer_server_ciphers on; #啟動加密演算法
  access_log /lw/logs/nginx/dataadmin.test.com.ssl.access.log access ; #日誌格式及日誌存放路徑
  error_log /lw/logs/nginx/dataadmin.test.com.ssl.error.log; #錯誤日誌存放路徑

}

-------------------------------------------------------------------------
}