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)
正則表達式舉例:
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組中.問題解決.
- 通過系統的信號控制 Nginx
使用信號加載新的配置
平滑升級到新的二進制代碼 - 使用Nginx限制下載速率和併發數
limit_zone limit_conn limit_rate - 使用Nginx進行地址轉發
rewrite
nginx rewrite中last和break的區別: http://blog.sina.com.cn/s/blog_4b01279a0100hd4c.html
6.Nginx Internals: Nginx源代碼、內部機制的分析
http://blog.zhuzhaoyuan.com/2009/09/nginx-internals-slides-video/
== 參考資料 ==
Nginx中文文檔:
http://wiki.nginx.org/NginxChs
服務器系統架構分析日誌:
http://www.sudone.com/
使用 Nginx 提升網站訪問速度:
http://www.ibm.com/developerworks/cn/web/wa-lo-nginx/