天天看點

Nginx_配置檔案nginx.conf配置詳解

user nginx nginx ;
    # Nginx使用者及組:使用者 組。window下不指定

worker_processes 8;
    # 工作程序:數目。根據硬體調整,通常等于CPU數量或者2倍于CPU。

error_log  logs/error.log;  
error_log  logs/error.log  notice;  
error_log  logs/error.log  info;  
    # 錯誤日志:存放路徑。

pid logs/nginx.pid;
    # pid(程序辨別符):存放路徑。

worker_rlimit_nofile 204800;
    # 指定程序可以打開的最大描述符:數目。
    # 這個指令是指當一個nginx程序打開的最多檔案描述符數目,理論值應該是最多打開檔案數(ulimit -n)與nginx程序數相除,
    # 但是nginx配置設定請求并不是那麼均勻,是以最好與ulimit -n 的值保持一緻。
    # 現在在linux 2.6核心下開啟檔案打開數為65535,worker_rlimit_nofile就相應應該填寫65535。
    # 這是因為nginx排程時配置設定請求到程序并不是那麼的均衡,是以假如填寫10240,總并發量達到3-4萬時就有程序可能超過10240了,這時會傳回502錯誤。

events{
    use epoll;
        # 使用epoll的I/O 模型。linux建議epoll,FreeBSD建議采用kqueue,window下不指定。
        # 補充說明: 與apache相類,nginx針對不同的作業系統,有不同的事件模型
            # A)标準事件模型
                # Select、poll屬于标準事件模型,如果目前系統不存在更有效的方法,nginx會選擇select或poll
            # B)高效事件模型
                # Kqueue:使用于FreeBSD 4.1+, OpenBSD 2.9+,NetBSD 2.0和MacOS X.使用雙處理器的MacOS X系統使用kqueue可能會造成核心崩潰。
                # Epoll:使用于Linux核心2.6版本及以後的系統。
                # /dev/poll:使用于Solaris 7 11/99+,HP/UX 11.22+ (eventport),IRIX 6.5.15+ 和 Tru64 UNIX 5.1A+。
                # Eventport:使用于Solaris 10。 為了防止出現核心崩潰的問題, 有必要安裝安全更新檔。
 
    worker_connections 204800;
        # 每個工作程序的最大連接配接數量。根據硬體調整,和前面工作程序配合起來用,盡量大,但是别把cpu跑到100%就行。
        # 每個程序允許的最多連接配接數,理論上每台nginx伺服器的最大連接配接數為。worker_processes*worker_connections

    keepalive_timeout 60;
        # keepalive逾時時間。

    client_header_buffer_size 4k;
        # 用戶端請求頭部的緩沖區大小。這個可以根據你的系統分頁大小來設定,一般一個請求頭的大小不會超過1k,
        # 不過由于一般系統分頁都要大于1k,是以這裡設定為分頁大小。分頁大小可以用指令getconf PAGESIZE 取得。
        # [root@web001 ~]# getconf PAGESIZE
        # 4096
        # 但也有client_header_buffer_size超過4k的情況,但是client_header_buffer_size該值必須設定為“系統分頁大小”的整倍數。

    open_file_cache max=65535 inactive=60s;
        # 這個将為打開檔案指定緩存,預設是沒有啟用的,max指定緩存數量,建議和打開檔案數一緻,inactive是指經過多長時間檔案沒被請求後删除緩存。

    open_file_cache_valid 80s;
        # 這個是指多長時間檢查一次緩存的有效資訊。

    open_file_cache_min_uses 1;
        # open_file_cache指令中的inactive參數時間内檔案的最少使用次數,如果超過這個數字,檔案描述符一直是在緩存中打開的,
        # 如上例,如果有一個檔案在inactive時間内一次沒被使用,它将被移除。
}

 

## 設定http伺服器,利用它的反向代理功能提供負載均衡支援

http{
    include mime.types;
        # 設定mime類型,類型由mime.type檔案定義

    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"';                    
    log_format log404 '$status [$time_local] $remote_addr $host$request_uri $sent_http_location';
        # 日志格式設定。
        # $remote_addr與$http_x_forwarded_for用以記錄用戶端的ip位址;
        # $remote_user:用來記錄用戶端使用者名稱;
        # $time_local: 用來記錄通路時間與時區;
        # $request: 用來記錄請求的url與http協定;
        # $status: 用來記錄請求狀态;成功是200,
        # $body_bytes_sent :記錄發送給用戶端檔案主體内容大小;
        # $http_referer:用來記錄從那個頁面連結通路過來的;
        # $http_user_agent:記錄客戶浏覽器的相關資訊;
        # 通常web伺服器放在反向代理的後面,這樣就不能擷取到客戶的IP位址了,通過$remote_add拿到的IP位址是反向代理伺服器的iP位址。
        # 反向代理伺服器在轉發請求的http頭資訊中,可以增加x_forwarded_for資訊,用以記錄原有用戶端的IP位址和原來用戶端的請求的伺服器位址。


    access_log  logs/host.access.log  main;
    access_log  logs/host.access.404.log  log404;
        # 用了log_format指令設定了日志格式之後,需要用access_log指令指定日志檔案的存放路徑;

    server_names_hash_bucket_size 128;
        # 儲存伺服器名字的hash表是由指令server_names_hash_max_size 和server_names_hash_bucket_size所控制的。
        # 參數hash bucket size總是等于hash表的大小,并且是一路處理器緩存大小的倍數。
        # 在減少了在記憶體中的存取次數後,使在處理器中加速查找hash表鍵值成為可能。
        # 如果hash bucket size等于一路處理器緩存的大小,那麼在查找鍵的時候,最壞的情況下在記憶體中查找的次數為2。
        # 第一次是确定存儲單元的位址,第二次是在存儲單元中查找鍵 值。
        # 是以,如果Nginx給出需要增大hash max size 或 hash bucket size的提示,那麼首要的是增大前一個參數的大小.

    client_header_buffer_size 4k;
        # 用戶端請求頭部的緩沖區大小。這個可以根據你的系統分頁大小來設定,一般一個請求的頭部大小不會超過1k,
        # 不過由于一般系統分頁都要大于1k,是以這裡設定為分頁大小。分頁大小可以用指令getconf PAGESIZE取得。

    large_client_header_buffers 8 128k;
        # 客戶請求頭緩沖大小。nginx預設會用client_header_buffer_size這個buffer來讀取header值,
        # 如果header過大,它會使用large_client_header_buffers來讀取。

    open_file_cache max=102400 inactive=20s;
        # 這個指令指定緩存是否啟用。
        # 例: open_file_cache max=1000 inactive=20s; 
        
    open_file_cache_errors
        # 這個指令指定是否在搜尋一個檔案是記錄cache錯誤。
        # 文法:open_file_cache_errors on | off 預設值:open_file_cache_errors off 使用字段:http, server, location 
        # 例:open_file_cache_errors on;

    open_file_cache_min_uses
        #這個指令指定了在open_file_cache指令無效的參數中一定的時間範圍内可以使用的最小檔案數,如果使用更大的值,檔案描述符在cache中總是打開狀态.
        #文法:open_file_cache_min_uses number 預設值:open_file_cache_min_uses 1 使用字段:http, server, location 
        #例:open_file_cache_min_uses 2; 
    
    open_file_cache_valid
        # 這個指令指定了何時需要檢查open_file_cache中緩存項目的有效資訊.
        # 文法:open_file_cache_valid time 預設值:open_file_cache_valid 60 使用字段:http, server, location 
        # 例:open_file_cache_valid 30s; 
        
    client_max_body_size 300m;
        # 設定通過nginx上傳檔案的大小

    sendfile on;
        # 指令指定 nginx 是否調用sendfile 函數(zero copy 方式)來輸出檔案,對于普通應用,必須設為on。
        # 如果用來進行下載下傳等應用磁盤IO重負載應用,可設定為off,以平衡磁盤與網絡IO處理速度,降低系統uptime。

    tcp_nopush on;
        # 此選項允許或禁止使用socke的TCP_CORK的選項,此選項僅在使用sendfile的時候使用

    proxy_connect_timeout 90; 
        # 後端伺服器連接配接的逾時時間_發起握手等候響應逾時時間

    proxy_read_timeout 180;
        # 連接配接成功後_等候後端伺服器響應時間_其實已經進入後端的排隊之中等候處理(也可以說是後端伺服器處理請求的時間)

    proxy_send_timeout 180;
        # 後端伺服器資料回傳時間_就是在規定時間之内後端伺服器必須傳完所有的資料

    proxy_buffer_size 256k;
        # 設定從被代理伺服器讀取的第一部分應答的緩沖區大小,通常情況下這部分應答中包含一個小的應答頭,
        # 預設情況下這個值的大小為指令proxy_buffers中指定的一個緩沖區的大小,不過可以将其設定為更小

    proxy_buffers 4 256k;
        # 設定用于讀取應答(來自被代理伺服器)的緩沖區數目和大小,預設情況也為分頁大小,根據作業系統的不同可能是4k或者8k

    proxy_busy_buffers_size 256k;

    proxy_temp_file_write_size 256k;
        # 設定在寫入proxy_temp_path時資料的大小,預防一個工作程序在傳遞檔案時阻塞太長

    proxy_temp_path /data0/proxy_temp_dir;
    
    proxy_cache_path /data0/proxy_cache_dir levels=1:2 keys_zone=cache_one:200m inactive=1d max_size=30g;
        # 設定記憶體緩存空間大小為200MB,1天沒有被通路的内容自動清除,硬碟緩存空間大小為30GB。
    # 注: proxy_temp_path 和 proxy_cache_path 指定的路徑必須在同一分區

    keepalive_timeout 120;
        # keepalive逾時時間。

    tcp_nodelay on;

    client_body_buffer_size 512k;
        # 如果把它設定為比較大的數值,例如256k,那麼,無論使用firefox還是IE浏覽器,來送出任意小于256k的圖檔,都很正常。
        # 如果注釋該指令,使用預設的client_body_buffer_size設定,也就是作業系統頁面大小的兩倍,8k或者16k,問題就出現了。
        # 無論使用firefox4.0還是IE8.0,送出一個比較大,200k左右的圖檔,都傳回500 Internal Server Error錯誤

    proxy_intercept_errors on;
        # 表示使nginx阻止HTTP應答代碼為400或者更高的應答。
    
    
    #定義負載均衡裝置的Ip及裝置狀态
    upstream bakend {
        server 127.0.0.1:8027;
        server 127.0.0.1:8028;
        server 127.0.0.1:8029;
        hash $request_uri;
    }
    """
        在需要使用負載均衡的server中增加 "proxy_pass http://bakend/;", bakend可以是任意字元串,隻要定義和引用一緻就行
        upstream目前支援的配置設定方式
        1、輪詢(預設)
            每個請求按時間順序逐一配置設定到不同的後端伺服器,如果後端伺服器down掉,能自動剔除。
        2、weight
            指定輪詢幾率,weight和通路比率成正比,用于後端伺服器性能不均的情況。
            例如:
            upstream bakend {
                server 192.168.0.14 weight=10;
                server 192.168.0.15 weight=10;
            }

        3、ip_hash
            每個請求按通路ip的hash結果配置設定,這樣每個訪客固定通路一個後端伺服器,可以解決session的問題。
            例如:
            upstream bakend {
                ip_hash;
                server 192.168.0.14:88;
                server 192.168.0.15:80;
            }

        4、fair(第三方)
            按後端伺服器的響應時間來配置設定請求,響應時間短的優先配置設定。
            例如:
            upstream backend {
                server server1;
                server server2;
                fair;
            }

        5、url_hash(第三方)
            按通路url的hash結果來配置設定請求,使每個url定向到同一個後端伺服器,後端伺服器為緩存時比較有效。
            注:在upstream中加入hash語句,server語句中不能寫入weight等其他的參數,hash_method是使用的hash算法
            例如:
            upstream backend {
                server squid1:3128;
                server squid2:3128;
                hash $request_uri;
                hash_method crc32;
            }

        upstream可為每個裝置設定的狀态:
            1.down:表示單前的server暫時不參與負載
            2.weight:weight越大,負載的權重就越大。
            3.max_fails:允許請求失敗的次數預設為1.當超過最大次數時,傳回proxy_next_upstream子產品定義的錯誤
            4.fail_timeout:max_fails次失敗後,暫停的時間。
            5.backup:其它所有的非backup機器down或者忙的時候,請求backup機器。是以這台機器壓力會最輕。
            例如:
            upstream bakend{
                ip_hash;
                server 127.0.0.1:9090 down;
                server 127.0.0.1:8080 weight=2;
                server 127.0.0.1:6060;
                server 127.0.0.1:7070 backup;
            }
        nginx支援同時設定多組的負載均衡,用來給不用的server來使用。
    """

    client_body_in_file_only
        # 設定為On,可以将client post過來的資料記錄到檔案中用來做debug
            
    client_body_temp_path
        # 設定記錄檔案的目錄,可以設定最多3層目錄

    # location對URL進行比對.可以進行重定向或者進行新的代理 負載均衡
}

 
##配置虛拟機

server{
    listen 80;
        #配置監聽端口

    server_name image.***.com;
        # 配置通路域名

    location ~* .(mp3|exe)$ {
        # 對以“mp3或exe”結尾的位址進行負載均衡

    proxy_pass http://img_relay$request_uri;
        # 設定被代理伺服器的端口或套接字,以及URL

    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        # 以上三行,目的是将代理伺服器收到的使用者的資訊傳到真實伺服器上
    }

    location /face {
        if ($http_user_agent ~* "xnp") {
            rewrite ^(.*)$ http://211.151.188.190:8080/face.jpg redirect;
        }
        proxy_pass http://img_relay$request_uri;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        error_page 404 502 = @fetch;
    }

    location @fetch {
        access_log /data/logs/face.log log404;
        rewrite ^(.*)$ http://211.151.188.190:8080/face.jpg redirect;
    }

    location /image {
        if ($http_user_agent ~* "xnp") {
            rewrite ^(.*)$ http://211.151.188.190:8080/face.jpg redirect;
        }
        proxy_pass http://img_relay$request_uri;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        error_page 404 502 = @fetch;
    }

    location @fetch {
        access_log /data/logs/image.log log404;
        rewrite ^(.*)$ http://211.151.188.190:8080/face.jpg redirect;
    }
}

 

##其他舉例

server{
    listen 80;
    
    server_name *.***.com *.***.cn;
    
    location ~* .(mp3|exe)$ {
        proxy_pass http://img_relay$request_uri;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    
    location / {
        if ($http_user_agent ~* "xnp") {
            rewrite ^(.*)$ http://i1.***img.com/help/noimg.gif redirect;
        }

        proxy_pass http://img_relay$request_uri;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        #error_page 404 http://i1.***img.com/help/noimg.gif;
        error_page 404 502 = @fetch;
    }

    location @fetch {
        access_log /data/logs/baijiaqi.log log404;

        rewrite ^(.*)$ http://i1.***img.com/help/noimg.gif redirect;
    }

}

server{
    listen 80;

    server_name *.***img.com;

    location ~* .(mp3|exe)$ {
        proxy_pass http://img_relay$request_uri;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location / {
        if ($http_user_agent ~* "xnp") {
            rewrite ^(.*)$ http://i1.***img.com/help/noimg.gif;
        }

        proxy_pass http://img_relay$request_uri;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        #error_page 404 http://i1.***img.com/help/noimg.gif;
        error_page 404 = @fetch;

    }

    #access_log off;

    location @fetch {
        access_log /data/logs/baijiaqi.log log404;

        rewrite ^(.*)$ http://i1.***img.com/help/noimg.gif redirect;
    }
}

server{
    listen 8080;

    server_name ngx-ha.***img.com;

    location / {
        stub_status on;

        access_log off;
    }
}

server {
    listen 80;

    server_name imgsrc1.***.net;

    root html;
}


server {
    listen 80;

    server_name ***.com w.***.com;

    # access_log /usr/local/nginx/logs/access_log main;

    location / {
        rewrite ^(.*)$ http://www.***.com/ ;
    }
}

server {
    listen 80;

    server_name *******.com w.*******.com;

    # access_log /usr/local/nginx/logs/access_log main;

    location / {
        rewrite ^(.*)$ http://www.*******.com/;
    }
}

server {
    listen 80;

    server_name ******.com;

    # access_log /usr/local/nginx/logs/access_log main;

    location / {
        rewrite ^(.*)$ http://www.******.com/;
    }
}

# 設定檢視Nginx狀态的位址
location /NginxStatus {
    stub_status on;
    access_log on;
    auth_basic "NginxStatus";
    auth_basic_user_file conf/htpasswd;
}


# 禁止通路.htxxx檔案
location ~ /.ht {
    deny all;
}


"""
注釋:變量
Ngx_http_core_module子產品支援内置變量,他們的名字和apache的内置變量是一緻的。

首先是說明客戶請求title中的行,例如$http_user_agent,$http_cookie等等。

此外還有其它的一些變量

$args此變量與請求行中的參數相等

$content_length等于請求行的“Content_Length”的值。

$content_type等同與請求頭部的”Content_Type”的值

$document_root等同于目前請求的root指令指定的值

$document_uri與$uri一樣

$host與請求頭部中“Host”行指定的值或是request到達的server的名字(沒有Host行)一樣

$limit_rate允許限制的連接配接速率

$request_method等同于request的method,通常是“GET”或“POST”

$remote_addr用戶端ip

$remote_port用戶端port

$remote_user等同于使用者名,由ngx_http_auth_basic_module認證

$request_filename目前請求的檔案的路徑名,由root或alias和URI request組合而成

$request_body_file

$request_uri含有參數的完整的初始URI

$query_string與$args一樣

$sheeme http模式(http,https)盡在要求是評估例如

Rewrite ^(.+)$ $sheme://example.com$; Redirect;

$server_protocol等同于request的協定,使用“HTTP/或“HTTP/

$server_addr request到達的server的ip,一般獲得此變量的值的目的是進行系統調用。為了避免系統調用,有必要在listen指令中指明ip,并使用bind參數。

$server_name請求到達的伺服器名

$server_port請求到達的伺服器的端口号

$uri等同于目前request中的URI,可不同于初始值,例如内部重定向時或使用index
"""