天天看點

Nginx基礎文法及常用配置

Nginx一般為開箱即用, 除了

nginx.conf

,其餘配置檔案,一般隻需要使用預設提供即可。

Nginx檔案結構

#全局塊
worker_process      # 表示工作程序的數量,一般設定為cpu的核數
worker_connections  # 表示每個工作程序的最大連接配接數           

events {}         #events塊

http      #http塊
{
	keepalive_timeout #連接配接逾時時間
    server        #server塊
    { 
        listen          # 監聽端口
    	server_name     # 監聽域名
        location [PATTERN]  #location塊
        {
			root        # 指定對應uri的資源查找路徑,這裡html為相對路徑
			index       # 指定首頁index檔案的名稱,可以配置多個,以空格分開。如有多個,按配置順序查找。
		}
    }
}
           
  • 全局塊:配置影響nginx全局的指令。 一般有運作nginx伺服器的使用者組,nginx程序pid存放路徑,日志存放路徑,配置檔案引入,允許生成worker process數等。
  • events塊:配置影響nginx伺服器或與使用者的網絡連接配接。 有每個程序的最大連接配接數,選取哪種事件驅動模型處理連接配接請求,是否允許同時接受多個網路連接配接,開啟多個網絡連接配接序列化等。
  • http塊:可以嵌套多個server,配置代理,緩存,日志定義等絕大多數功能和第三方子產品的配置。 如檔案引入,mime-type定義,日志自定義,是否使用sendfile傳輸檔案,連接配接逾時時間,單連接配接請求數等。
  • server塊:配置虛拟主機的相關參數,一個http中可以有多個server。
  • 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  my_log '"$http_x_forwarded_for" $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent $request_time $upstream_response_time "$http_referer" "$http_user_agent" "$scheme"'; #自定義日志格式

    sendfile on;   #允許sendfile方式傳輸檔案,預設為off,可以在http塊,server塊,location塊。
    sendfile_max_chunk 100k;  #每個程序每次調用傳輸數量不能大于設定的值,預設為0,即不設上限。
    keepalive_timeout 65;  #連接配接逾時時間,預設為75s,可以在http,server,location塊。

    upstream webservers {   
      server 127.0.0.1:8001;
      server 192.168.1.1:8001 backup;  #熱備
    }
    
    error_page 404 @page_not_found; #錯誤頁
    server {
        keepalive_requests 120; #單連接配接請求上限次數。
        listen       80; #監聽端口
        listen 443 ssl;
        ssl on;
        ssl_certificate         /data/var/example.com.crt;
        ssl_certificate_key     /data/var/example.com.key;
        server_name  www.exapmle.com;   #監聽位址       
        access_log /data/weblog/nginx/access.log my_log;  #combined為日志格式的預設值

        location  ~*^.+$ {       #請求的url過濾,正則比對,~為區分大小寫,~*為不區分大小寫。
           proxy_pass  http://webservers;  #請求轉向upstream定義的伺服器清單
           deny 127.0.0.1;  #拒絕的ip
           allow 192.168.1.1; #允許的ip           
        } 

        location ~ \.(html)$ {
            root   /data/webapps/static/; #根目錄
            index  index.html index.htm;  #設定預設頁
            concat on;
        }

		location @page_not_found {
			proxy_set_header Host $host;
			proxy_pass http://webservers;
			error_page 404 = /404.html;
		}
    }
}
           
Nginx常用内置綁定變量

Nginx基礎文法

upstream

HTTP Upstream

子產品中,可以通過 server 指令指定後端伺服器的 IP 位址和端口,同時還可以設定每個後端伺服器在負載均衡排程中的狀态。常用的狀态有:

  • down

    :表示目前的 server 暫時不參與負載均衡。
  • backup

    :預留的備份機器。當其他所有的非 backup 機器出現故障或者忙的時候,才會請求 backup 機器,是以這台機器的壓力最輕。
  • max_fails

    :允許請求失敗的次數,預設為 1 。當超過最大次數時,傳回 proxy_next_upstream 子產品定義的錯誤。
  • fail_timeout

    :在經曆了 max_fails 次失敗後,暫停服務的時間。max_fails 可以和 fail_timeout 一起使用。
當負載排程算法為

ip_hash

時,後端伺服器在負載均衡排程中的狀态不能是

backup

配置示例:

upstream webservers {
    server 192.168.18.201 weight=1 max_fails=2 fail_timeout=2;
    server 192.168.18.202 weight=2 max_fails=2 fail_timeout=2;
    server 192.168.18.203 down;
    server 127.0.0.1:8080 backup;
}
           

上述配置中

192.168.18.203

不參與負載均衡,

127.0.0.1:8080

為備機,根據該權重配置, 2 3 \frac{2}{3} 32​的請求量會到

192.168.18.202

,另外 1 3 \frac{1}{3} 31​的請求量會到

192.168.18.201

upstream支援的負載均衡算法見負載均衡

rewrite

rewrite 文法

  • last

    – 發起一個新的請求,再次進入server塊,重試location比對
  • break

    – 中止 rewrite,不再繼續比對
  • redirect

    – 傳回臨時重定向的 HTTP 狀态 302
  • permanent

    – 傳回永久重定向的 HTTP 狀态 301
如果location中rewrite後是對靜态資源的請求,不需要再進行其他比對,一般要使用

break

或不寫,直接使用目前location中的資料源,完成本次請求

如果location中rewrite後,還需要進行其他處理,如動态fastcgi請求(.php,.jsp)等,要用

last

繼續發起新的請求

配置示例:

server {
    listen 80;
    server_name www.example.com;
    index index.html index.htm;
    root html;
    if ($http_host !~ "^www\.example\.cn$") {
        rewrite ^(.*) http://www.example.com$1 redirect;
    }
    
	rewrite ^/web$ /web_static/index.html last;
    rewrite ^/watch/index.htm$ $scheme://www.example.com/watch permanent;
    
    location ^~ /web_static/ {
         rewrite ^/web_static/([\S]+) /$1 break;
         proxy_set_header Host web.example.com;
         proxy_set_header Remote-Host http://www.example.com;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
         proxy_pass https://web.example.com/;
         proxy_http_version 1.1;
         error_page 404 = @page_not_found;
     }
     
     location ^~ /html/ {
         root  /data/webapps/static/;
         try_files /read/$uri /back/$uri @page_not_found;
     }
}

           

費力的rewrites

不要知難而退,rewrite 很容易和正規表達式混為一談。 實際上,rewrite 是很容易的,我們應該努力去保持它們的整潔。 很簡單,不添加備援代碼就行了。

糟糕的配置:

好點兒的配置:

更好的配置:

反複對比下這幾個配置。 第一個 rewrite 捕獲不包含第一個斜杠的完整 URI。 使用内置的變量

$request_uri

,我們可以有效的完全避免任何捕獲和比對。

參考資料:

  1. Nginx wiki
  2. Pitfalls and Common Mistakes
  3. Nginx 内置綁定變量
  4. Nginx 陷阱和常見錯誤
  5. Full Example Configuration

繼續閱讀