1. 程式人生 > >Nginx入門筆記之————配置檔案結構

Nginx入門筆記之————配置檔案結構

Nginx入門筆記之————配置檔案結構

 

...              #全域性塊

events {         #events塊
   ...
}

http      #http塊
{
    ...   #http全域性塊
    server        #server塊
    { 
        ...       #server全域性塊
        location [PATTERN]   #location塊
        {
            ...
        }
        location [PATTERN] 
        {
            ...
        }
    }
    server
    {
      ...
    }
    ...     #http全域性塊
}

 

1、全域性塊:配置影響nginx全域性的指令。一般有執行nginx伺服器的使用者組,nginx程序pid存放路徑,日誌存放路徑,配置檔案引入,允許生成worker process數等。

2、events塊:配置影響nginx伺服器或與使用者的網路連線。有每個程序的最大連線數,選取哪種事件驅動模型處理連線請求,是否允許同時接受多個網路連線,開啟多個網路連線序列化等。

3、http塊:可以巢狀多個server,配置代理,快取,日誌定義等絕大多數功能和第三方模組的配置。如檔案引入,mime-type定義,日誌自定義,是否使用sendfile傳輸檔案,連線超時時間,單連線請求數等。

4、server塊:配置虛擬主機的相關引數,一個http中可以有多個server。

5、location塊:配置請求的路由,以及各種頁面的處理情況。

########### 每個指令必須有分號結束。#################
#user administrator administrators;  #配置使用者或者組,預設為nobody nobody。
#worker_processes 2;  #允許生成的程序數,預設為1
#pid /nginx/pid/nginx.pid;   #指定nginx程序執行檔案存放地址
error_log log/error.log debug;  #制定日誌路徑,級別。這個設定可以放入全域性塊,http塊,server塊,級別以此為:debug|info|notice|warn|error|crit|alert|emerg
events {
    accept_mutex on;   #設定網路連線序列化,防止驚群現象發生,預設為on
    multi_accept on;  #設定一個程序是否同時接受多個網路連線,預設為off
    #use epoll;      #事件驅動模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
    worker_connections  1024;    #最大連線數,預設為512
}
http {
    include       mime.types;   #副檔名與檔案型別對映表
    default_type  application/octet-stream; #預設檔案型別,預設為text/plain
    #access_log off; #取消服務日誌    
    log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定義格式
    access_log log/access.log myFormat;  #combined為日誌格式的預設值
    sendfile on;   #允許sendfile方式傳輸檔案,預設為off,可以在http塊,server塊,location塊。
    sendfile_max_chunk 100k;  #每個程序每次呼叫傳輸數量不能大於設定的值,預設為0,即不設上限。
    keepalive_timeout 65;  #連線超時時間,預設為75s,可以在http,server,location塊。

    upstream mysvr {   
      server 127.0.0.1:7878;
      server 192.168.10.121:3333 backup;  #熱備
    }
    error_page 404 https://www.baidu.com; #錯誤頁
    server {
        keepalive_requests 120; #單連線請求上限次數。
        listen       4545;   #監聽埠
        server_name  127.0.0.1;   #監聽地址       
        location  ~*^.+$ {       #請求的url過濾,正則匹配,~為區分大小寫,~*為不區分大小寫。
           #root path;  #根目錄
           #index vv.txt;  #設定預設頁
           proxy_pass  http://mysvr;  #請求轉向mysvr 定義的伺服器列表
           deny 127.0.0.1;  #拒絕的ip
           allow 172.18.5.54; #允許的ip           
        } 
    }
}

 

########### 每個指令必須有分號結束。#################
#配置使用者或者組,預設為nobody nobody。
#user administrator administrators;  
 
#允許生成的程序數,預設為1
#worker_processes 2;  
 
#指定nginx程序執行檔案存放地址
#pid /nginx/pid/nginx.pid;   
 
#制定日誌路徑,級別。這個設定可以放入全域性塊,http塊,server塊,級別以此為:#debug|info|notice|warn|error|crit|alert|emerg
error_log logs/error.log debug;  
 
#最大檔案開啟數(連線),可設定為系統優化後的ulimit -HSn的結果
worker_rlimit_nofile 51200;
 
events {
    #設定網路連線序列化,防止驚群現象發生,預設為on
    accept_mutex on;   
 
    #設定一個程序是否同時接受多個網路連線,預設為off
    multi_accept on;  
 
     #事件驅動模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
    #use epoll; 
 
    #最大連線數,預設為512    
    worker_connections  1024;    
}
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;
 
    #第三方模組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;
 
    #取消服務日誌    
    #access_log off;
 
    #自定義格式
    log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; 
 
    #combined為日誌格式的預設值
    access_log logs/access.log myFormat;  
 
    #開啟高效傳輸模式,允許sendfile方式傳輸檔案,預設為off,可以在http塊,server塊,location塊。
    sendfile on;   
 
    #每個程序每次呼叫傳輸數量不能大於設定的值,預設為0,即不設上限。
    sendfile_max_chunk 100k; 
 
    #連線超時時間,預設為75s,可以在http,server,location塊。
    keepalive_timeout 65;  
 
    #啟用tcp_nopush引數可以允許把httpresponse header和檔案的開始放在一個檔案裡釋出,積極的作用是減少網路報文段的數量
    #tcp_nopush     on;
    #啟用tcp_nodelay,核心會等待將更多的位元組組成一個數據包,從而提高I/O效能
    #tcp_nodelay on;
 
 
    #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;
 
    #開啟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;
 
        
    #反向代理負載均衡設定部分
    #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次失敗即認為主機不可用!
  }
 
    #定義的伺服器列表
    upstream mysvr {   
      server 127.0.0.1:7878;
      server 192.168.10.121:3333 backup;  #熱備
    }
 
    error_page 404 https://www.baidu.com; #錯誤頁
    server {
        #單連線請求上限次數。
        keepalive_requests 120; 
 
        #監聽埠
        listen       4545;   
 
        #監聽地址  
        server_name  127.0.0.1;      
        #server_name  www.abc.com abc.com;   
 
        #error_page 500 502 404 /templates/kumi/phpcms/404.html;   #錯誤頁面
 
        # 或者重定向405錯誤
        error_page 405 =200 @405;
        location @405 {
            root  $rootpath;
            proxy_method GET;
            proxy_pass http://static_backend;
            allow all;
        }  
 
        #偽靜態   將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;
 
        
 
        #請求的url過濾,正則匹配,~為區分大小寫,~*為不區分大小寫。
        location  ~*^.+$ {   '
           #根目錄   
           #root path;
  
           #設定預設頁
           #index vv.txt;  
 
           #請求轉向mysvr 定義的伺服器列表
           proxy_pass  http://mysvr;  
 
           #拒絕的ip
           deny 127.0.0.1;  
           #禁止其他ip訪問
           #deny all;            
 
           #允許的ip  
           allow 172.18.5.54;          
        } 
 
        #將符合js,css檔案的等設定expries快取引數,要求瀏覽器快取。
        location~ .*\.(js|css)?$ {
           #客戶端快取上述js,css資料30天
           expires 30d; 
        }
 
        # 故障轉移
        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;
        }
 
 
 
        ##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########
    }
 
    -----------------------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; #錯誤日誌存放路徑
 
    }
    -------------------------------------------------------------------------
}