1. 程式人生 > >Nginx 入門教程常用配置解析

Nginx 入門教程常用配置解析

Nginx介紹和安裝

Nginx是一個自由、開源、高效能及輕量級的HTTP伺服器及反轉代理伺服器,
其效能與IMAP/POP3代理伺服器相當。Nginx以其高效能、穩定、功能豐富、配置簡單及佔用系統資源少而著稱。
Nginx 超越 Apache 的高效能和穩定性,使得國內使用 Nginx 作為 Web 伺服器的網站也越來越多.

*基礎功能
處理靜態檔案,索引檔案以及自動索引;
反向代理加速(無快取),簡單的負載均衡和容錯;
FastCGI,簡單的負載均衡和容錯;
模組化的結構。過濾器包括gzipping, byte ranges, chunked responses, 以及 SSI-filter 。在SSI過濾器中,到同一個 proxy 或者 FastCGI 的多個子請求併發處理;
SSL 和 TLS SNI 支援;

*優勢
Nginx專為效能優化而開發,效能是其最重要的考量, 實現上非常注重效率 。它支援核心Poll模型,能經受高負載的考驗, 有報告表明能支援高達 50,000 個併發連線數。
Nginx作為負載均衡伺服器: Nginx 既可以在內部直接支援 Rails 和 PHP 程式對外進行服務, 也可以支援作為 HTTP代理伺服器對外進行服務。
Nginx具有很高的穩定性。其它HTTP伺服器,當遇到訪問的峰值,或者有人惡意發起慢速連線時,也很可能會導致伺服器實體記憶體耗盡頻繁交換,失去響應,只能重啟伺服器。
例如當前apache一旦上到200個以上程序,web響應速度就明顯非常緩慢了。而Nginx採取了分階段資源分配技術,使得它的CPU與記憶體佔用率非常低。
nginx官方表示保持10,000個沒有活動的連線,它只佔2.5M記憶體,就穩定性而言, nginx比lighthttpd更勝一籌。
Nginx支援熱部署。它的啟動特別容易, 並且幾乎可以做到7*24不間斷執行,即使執行數個月也不需要重新啟動。你還能夠在不間斷服務的情況下,對軟體版本進行進行升級。
Nginx採用C進行編寫, 不論是系統資源開銷還是CPU使用效率都比 Perlbal 要好很多。

*nginx的安裝

開發穩定版: Nginx 0.8.X
當前穩定版: Nginx 0.7.X
歷史穩定版: Nginx 0.6.X

1)pcre安裝,支援正則表示式

http://www.pcre.org/

# tar zxvf pcre-7.9.tar.gz

# cd pcre-7.9

#./configure

# make && make install 

2)openssl安裝(可選),支援安全協議的站點

http://www.openssl.org/

# tar zxvf openssl-0.9.8l.tar.gz

# cd openssl-0.9.8l

#./config
# make && make install 3)nginx的安裝 # tar zxvf nginx-0.7.64.tar.gz # cd nginx-0.7.64 配置安裝和不安裝元件:--with-MODULE_NAME or --without-MODULE_NAME # ./configure --prefix=/usr/local/nginx/nginx8011 --with-openssl=/usr/include/openssl --with-http_stub_status_module # make && make install 目錄結構: conf 配置檔案 html 靜態頁面 logs 日誌檔案 sbin 主程式 4)啟動 # /usr/local/nginx/nginx8011/sbin/nginx //啟動 啟動引數: -c </path/to/config> 為 Nginx 指定一個配置檔案,來代替預設的。 -t 不執行,而僅僅測試配置檔案。nginx 將檢查配置檔案的語法的正確性,並嘗試開啟配置檔案中所引用到的檔案。 -v 顯示 nginx 的版本。 -V 顯示 nginx 的版本,編譯器版本和配置引數。 不啟動,僅測試配置檔案:/usr/bin/nginx -t -c ~/mynginx.conf 5)配置自啟動

== 一個簡單的配置檔案 ==

#-----------------------------------基本模組

# 使用的使用者和組

user  www www;

# 指定工作程序數

worker_processes  1;

# 可以使用 [ debug | info | notice | warn | error | crit ]  引數

#error_log  logs/error.log;

#error_log  logs/error.log  notice;

# 指定 pid 存放的路徑

#pid        logs/nginx.pid;

#-----------------------------------事件模組 

events {

#每個worker的最大連線數

    worker_connections  1024;

}

#-----------------------------------HTTP 模組 

http {

#包含一個檔案描述了:不同檔案字尾對應的MIME,見案例分析

    include       mime.types;

#制定預設MIME型別為二進位制位元組流

    default_type  application/octet-stream;

#指令 access_log 指派路徑、格式和快取大小。

    #access_log  off;

#開啟呼叫Linux的sendfile(),提供檔案傳輸效率

    sendfile        on;

#是否允許使用socket的TCP_NOPUSH或TCP_CORK選項

    #tcp_nopush     on;

    #指定客戶端連線保持活動的超時時間,在這個時間之後,伺服器會關掉連線。

    keepalive_timeout  65;

#設定gzip,壓縮檔案

    #gzip  on;

#為後端伺服器提供簡單的負載均衡

upstream apaches {

server 127.0.0.1:8001;

server 127.0.0.1:8002;

}

#配置一臺虛擬機器

    server {

        listen       8012;

        server_name  localhost;

        location / {

proxy_pass http://apaches;

        }
    }
}

== 模組介紹 ==
模組劃分:
Core 核心模組
Events 事件模組
HTTP HTTP模組
Mail 郵件模組

*核心模組的常用元件

user 

語法: user user [group] 

預設值: nobody nobody 

指定Nginx Worker程序執行使用者,預設是nobody帳號。

error_log 

語法: error_log file [ debug | info | notice | warn | error | crit ] 

預設值: ${prefix}/logs/error.log 

制定錯誤日誌的存放位置和級別。

include 

語法: include file | * 

預設值: none 

include 指令還支援像下面配置一樣的全域性包含的方法,例如包含一個目錄下所有以".conf"結尾的檔案: include vhosts/*.conf;

pid 

語法: pid file 

程序id儲存檔案。可以使用 kill -HUP cat /var/log/nginx.pid/ 對Nginx進行配置檔案重新載入。 

worker_processes 

語法: worker_processes number 

預設值: 1 

指定工作程序數。nginx可以使用多個worker程序。

事件模組的常用元件

worker_connections 

語法:worker_connections number 

通過worker_connections和worker_proceses可以計算出maxclients: max_clients = worker_processes * worker_connections

作為反向代理,max_clients為: max_clients = worker_processes * worker_connections/4 ,因為瀏覽器訪問時會通過連線池建立多個連線。

use 

語法:use [ kqueue | rtsig | epoll | /dev/poll | select | poll | eventport ] 

如果在./configure的時候指定了不止一種事件模型,那麼可以設定其中一個,以便告訴nginx使用哪種事件模型。預設情況下nginx會在./configure時找出最適合系統的事件模型。

事件模型是指Nginx處理連線的方法。

HTTP模組的核心元件和變數

三個作用域:http, server, location 

server

語法:server {...} 

作用域: http 

配置一臺虛擬機器。

location 

語法: location [=|~|~*|^~] /uri/ { ... } 

作用域: server 

配置訪問路徑的處理方法。

listen 

語法: listen address:port [ default [ backlog=num | rcvbuf=size | sndbuf=size | accept_filter=filter | deferred | bind | ssl ] 

預設值: listen 80 

作用域: server 

指定當前虛擬機器的監聽埠。

alias 

語法: alias file-path|directory-path; 

作用域: location 

該指令設定指定location使用的路徑.注意它跟 root 相似,但是不改變檔案的根路徑,僅僅是使用檔案系統路徑 

root 

語法: root path 

預設值:root html 

作用域:http, server, location

alias指定的目錄是準確的,root是指定目錄的上級目錄,並且該上級目錄要含有location指定名稱的同名目錄。

區別:

location /abc/ {

alias /home/html/abc/;

}

在這段配置下,http://test/abc/a.html就指定的是/home/html/abc/a.html。這段配置亦可改成

location /abc/ {

root /home/html/;

}

這樣,nginx就會去找/home/html/目錄下的abc目錄了,得到的結果是相同的。

HTTP模組的其他基本元件將結合案例介紹。

變數:

HTTP header 裡邊 特定HEADER的值,變數會轉成小寫,比如 $http_user_agent, $http_referer... header資訊 "YOUR-STRANGE-HEADER: values" 能通過 $http_your_strange_header獲得. 

$arg_PARAMETER 

$http_HEADER 

$query_string = $args 

郵件模組的常用元件(略)
== 常用場景配置 ==
1.多臺伺服器配置負載均衡

http {

    include       mime.types;

    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;

upstream allserver {

#ip_hash;

server 127.0.0.1:8083 down; 

server 127.0.0.1:8084 weight=3; 

server 127.0.0.1:8001; 

server 127.0.0.1:8002 backup; 

}
    server {

        listen       8012;

        server_name  localhost;

        location / {

            proxy_pass http://allserver;

        }
    }
}

ip_hash; nginx中的ip_hash技術能夠將某個ip的請求定向到同一臺後端,這樣一來這個ip下的某個客戶端和某個後端就能建立起穩固的session

1.down 表示單前的 server 暫時不參與負載
2.weight 預設為 1.weight 越大,負載的權重就越大。
3.backup: 其它所有的非 backup 機器 down 或者忙的時候,請求 backup機器。所以這臺機器壓力會最輕。

2.通過手機客戶端的頭資訊或者請求的引數轉發到不用目錄

http {

    include       mime.types;

    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;

upstream apaches {

server 127.0.0.1:8001;

server 127.0.0.1:8002;

}

upstream tomcats {

server 127.0.0.1:8083;

server 127.0.0.1:8084;

}
    server {

        listen       8012;

        server_name  localhost;

        location / {

set $ismob 0;

# 注意if後的空格

if ( $http_chip ~* "(NOKIA3500)|(NOKIA3200)" )

{

set $ismob 1;

proxy_pass http://apaches;

}

if ( $http_chip ~* "(NOKIA3500)|(NOKIA3200)" )

{

set $ismob 1;

proxy_pass http://tomcats;

}

            if ( $ismob = 0 )

{

root /usr/local/nginx/nginx8012/html;

}
        }

location ~* /rewrite/testXID.jsp {

if ( $arg_XID = "13800138000")

{

rewrite ^(.*)$ http://192.168.0.190:8084/testSID.jsp break; 

}

}
    }

}

1、正則表示式匹配,其中:
= 完全相等;
~為區分大小寫匹配;
~*為不區分大小寫匹配;
!~和!~*分別為區分大小寫不匹配及不區分大小寫不匹配。
2、檔案及目錄匹配,其中:
-f和!-f用來判斷是否存在檔案;
-d和!-d用來判斷是否存在目錄;
-e和!-e用來判斷是否存在檔案或目錄;
-x和!-x用來判斷檔案是否可執行。
if (-d $request_filename){ … }

哪些地方會出現正則表示式:
1.location ~* /.(gif|jpg|png|swf|flv)2.rewrite(.) /nginx-ie/$1 break;

正則表示式舉例:
1.多目錄轉成引數 abc.domian.com/sort/2 => abc.domian.com/index.php?act=sort&name=abc&id=2
if (host ~* (.*)/.domain/.com) {   
set $sub_name $1;  
rewrite ^/sort//(/d+)//?$ /index.php?act=sort&cid=$sub_name&id=$1 last;   
}  
2.目錄對換 /123456/xxxx -> /xxxx?id=123456  
rewrite ^/(/d+)/(.+)/ /
2?id=$1 last;

3.防盜鏈

http {

    include       mime.types;

    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;

    server {

        listen       8012;

        server_name  localhost;

        location / {

root html;

        }

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

valid_referers none blocked server_names http://localhost baidu.com; 

if ($invalid_referer) { 

 rewrite ^/ html/50x.html; 

}

}
    }

}

4.訪問控制:身份驗證、限制IP

http {

    include       mime.types;

    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;

upstream tomcats {

server 127.0.0.1:8083;

server 127.0.0.1:8084;

}
    server {

        listen       8012;

        server_name  localhost;

        location / {

allow 192.168.4.8;

deny all;

auth_basic  "index";

auth_basic_user_file ../htpasswd;

proxy_pass http://tomcats;

        }
    }
}

cp /usr/local/apache/apache8001/bin/htpasswd /usr/local/bin/
/usr/local/bin/htpasswd -c htpasswd root

5.檢視Nginx的執行狀態

http {

    include       mime.types;

    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;

upstream apaches {

server 127.0.0.1:8001;

server 127.0.0.1:8002;

}

upstream tomcats {

server 127.0.0.1:8083;

server 127.0.0.1:8084;

}

    server {

        listen       8012;

        server_name  localhost;

        location / {

proxy_pass http://tomcats;

        }

        location /NginxStatus {

stub_status on;

access_log  off;

auth_basic  "NginxStatus";

auth_basic_user_file ../htpasswd;

        }
    }
}

== 進階內容 ==
1.檢視Nginx的執行狀態

Active connections: 364
server accepts handled requests
5477919 5477919 17515830
Reading: 10 Writing: 26 Waiting: 328

意思如下:
active connections – 當前 Nginx 正處理的活動連線數。
serveraccepts handled requests – 總共處理了 5477919 個連線 , 成功建立 5477919 次握手 (證明中間沒有失敗的 ), 總共處理了 17515830 個請求 ( 平均每次握手處理了 3.2 個數據請求 )。
reading – nginx 讀取到客戶端的 Header 資訊數。
writing – nginx 返回給客戶端的 Header 資訊數。
waiting – 開啟 keep-alive 的情況下,這個值等於 active - (reading + writing),意思就是 Nginx 已經處理完正在等候下一次請求指令的駐留連線。

2.案例分析:

將web server由apache換為nginx後,卻帶來意想不到的問題.多個頁面顯示模組顯示”正在載入中…”然後一直停頓,使用FireBug除錯前端,XSL檔案解析失敗.但載入又是HTTP 200 的正常狀態.
繼續用FireBug除錯,發現XSL檔案下載時的HTTP響應頭中,
Content-Type是oct/stream ,而在原來的apache中,是text/xml,於是修改/etc/nginx/mime.types檔案.將XSL的副檔名加到xml組中.問題解決.

  1. 通過系統的訊號控制 Nginx
    使用訊號載入新的配置
    平滑升級到新的二進位制程式碼
  2. 使用Nginx限制下載速率和併發數
    limit_zone limit_conn limit_rate