nginx:
nginx是俄羅斯軟件工程師Igor Sysoev開發的免費開源web服務器軟件,nginx採用了模塊化、事件驅動、異步、單線程及非阻塞的架構,並大量採用了多路複用及事件通知機制來實現高併發和高性能,解決C10K的問題,主要功能就是提供http和反向代理服務,以及郵件服務及反向代理等,並且具有多種web服務器功能特性:負載均衡,緩存,訪問控制,帶寬控制,以及高效整合各種應用的能力。
在nginx中,連接請求由爲數不多的幾個僅包含一個線程的進程worker以高效的迴環(run-loop)機制進行處理,而每個worker可以並行處理數千個的併發連接及請求。
nginx特性:
1、 模塊化設計,較好的擴展性;
2、 高可靠性:由一個master主進程和多個worker子進程
3、 支持熱部署:平滑升級版本
不停機更新配置文件、更換日誌文件、更新服務器程序版本
4、 低內存消耗
10000個keep-alive連接模式下的非活動連接僅消耗2.5M內存
nginx的基本功能:
靜態資源的web服務器;
http協議的反向代理服務器
pop3/imap4協議反向代理服務器
FastCGI,uWSGI等協議;
模塊化(非DSO),不支持動態裝卸載
一、nginx的配置詳解(用淘寶研發的tengine作爲例子):
user nginx nginx; //指定用於運行worker進程的用戶和組 worker_processes 4; //指定nginx運行的子進程數,通過時CPU核心數-1 error_log logs/error.log info; //全局錯誤日誌,類型爲info pid logs/nginx.pid; //nginx運行時的PID worker_rlimit_nofile_number 2048; //當個worker進程所能打開的最大連接數 worker_rlimit_sigpending 100; //指定每個用戶能夠發往worker進程的信號的數量 worker_cpu_affinity cpumask ...; 和cpu做綁定,主要作用是均衡的使用cpu 4顆cpu的話: worker_cpu_affinity 0001 0010 0100 1000; worker_priority nice : 調整work子進程的nice值
設定工作模式及連接數:
events { worker_connections 1024; //單個worker能響應的最大併發連接數 use [epoll|rgsig|select|poll]; //定義使用的事件模型;建議讓Nginx自動選擇 accept_mutex [on|off]; //內部調用用戶請求至各worker時用的負載均衡鎖;打開時表示能讓多個worker輪流地、序列化地與響應新請求; lock_file /path/to/lock_file; //鎖文件, accept_mutex_delay #ms; //內部調用用戶請求至各worker時的延遲時間 }
設定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"'; //日誌的格式 access_log logs/access.log main; //訪問日誌的存放路徑 sendfile on; //sendfile函數,對於普通應用,必須設爲on,如果用來進行下載等應用磁盤IO重負載應用,可設置爲off,以平衡磁盤與網絡I/O處理速度,降低系統的uptime. tcp_nopush on; // 是否啓用TCP_NOPUSH(FREEBSE)或TCP_CORK(Linux)選項;僅在sendfile爲on時有用; keepalive_timeout 65; // 設定keepalive連接的超時時長;0表示禁止長連接;默認爲75s; tcp_nodelay on|off; // 對keepalive模式下的連接是否使用TCP_NODELAY選項; gzip on; // 是否啓用gzip壓縮報文的body keepalive_requests number; //在keepalived連接上所允許請求的最大資源數量;默認爲100; keepalive_disable none | browser ...; //指明禁止爲何種瀏覽器使用keepalive功能; send_timeout 60; //向客戶端發送響應報文的超時時長,默認爲60s client_body_buffer_size 512k; //接收客戶請求報文body的緩衝區大小;默認爲16k;超出此指定大小時,其將被移存於磁盤上 client_body_temp_path path [level1 [level2 [level3]]]; //設定用於存儲客戶端請求報文的body的臨時存儲路徑及子目錄結構和數量; client_header_buffer_size 1k; //設置客戶請求報文首部的緩衝區大小 large_client_header_buffers 4 4k; //設置請求報文大首部的緩衝區大小 aio on|off; //是否打開異步傳輸的功能,默認是關閉的 directio size|off; //設置直接IO的大小及是否關閉 open_file_cache max=65535 inactive=20s; //是否開啓文件描述符緩存 open_file_cache_errors on | off //是否緩存找不到其路徑的文件,或沒有權限沒有權限訪問的文件相關信息 open_file_cache_valid 30s; //每隔多久檢查一次緩存中緩存項的有效性;默認爲60s; open_file_cache_min_uses number 1 //緩存項在非活動期限內最少應該被訪問的次數,指定被訪問次數的多少纔算是最少訪問
server服務:
server { listen 80; //監聽的端口 server_name localhost; //虛擬主機名稱 access_log logs/host.access.log main; //訪問本虛擬機服務的日誌 location /admin/ { //匹配客戶端請求的URL root html; //指定Document的路徑,在安裝目錄的html目錄下 index index.html index.htm; //默認主頁 } =: URI的精確匹配; location = /admin/ ~: 做正則表達式匹配,區分字符大小寫; ~*:做正則表達式匹配,不區分字符大小寫; ^~:對URI的左半部分匹配,不區分字符大小寫; 匹配優先級:精確匹配= > ^~ > ~或~* > 不帶符號的URI; location /images/ { alias /data/imgs/; //定義location匹配的別名 } error_page 404 /404.html; //錯誤頁面 error_page 500 502 503 504 /50x.html; //服務器端錯誤頁面 location = /50x.html { root html; } location /download/ { imit_except GET { allow 172.16.0.0/16; //只有172.18.0.0的主機能用其他方法,其他主機只能get deny all; } } location /download/ { limit rate 20480; //限制客戶端每秒鐘所能夠傳輸的字節數,默認爲0表示無限制 }
二、nginx的模塊詳解:
1、ngx_http_access_module (實現訪問控制)
allow address | CIDR | unix: | all;
deny address | CIDR | unix: | all;
2、ngx_http_auth_basic_module (實現basic認證)
2.1 auth_basic string | off 使用http basic認證協議對用戶進行認證; 2.2 auth_basic_user_file file; 實現用戶認證的賬號文件 location /admin/ { auth_basic "Admin Area"; auth_basic_user_file /etc/nginx/.ngxhtpasswd; }
3、ngx_http_log_module (現實日誌功能的模塊)
3.1 log_format name string ...; 定義日誌格式及其名稱 log_format compression '$remote_addr - $remote_user [$time_local] ' '"$request" $status $bytes_sent ' '"$http_referer" "$http_user_agent" "$gzip_ratio"'; 3.2 access_log path [format [buffer=size [flush=time]]]; path: 日誌存放路徑 format: 日誌格式 默認爲combined格式 buffer: 日誌緩存大小 flush: 刷寫時間間隔 3.3 open_log_file_cache max=N [inactive=time] [min_uses=N] [valid=time] open_log_file_cache off 關閉日誌緩存功能 max: 最大緩存的條目 inactive:緩存的活動時間 min_user: 在緩存時間內的最小使用次數 valid: 檢查緩存裏文件描述符的有效性
4、ngx_http_stub_status_module (實現顯示nginx的狀態)
location /status { stub_status; } Active connections:當前活動的客戶端連接數; accepts:已經接受的客戶端連接總數; handled:已經處理過後客戶端連接總數; requests:客戶端的總的請求數; Readking:正在讀取的客戶端請求報文首部的連接數; Writing:正向其發送響應報文的連接數; Waiting:等待客戶端發出請求的空閒連接數;
5、ngx_http_referer_module (基於請求報文中的Referer首部的值做訪問控制)
valid_referers none | blocked | server_names | string ...; 定義合法的請求 none:請求報文不存在referer首部; blocked:請求報文中存在referer首部,但其沒有有效值,或其值非以http://或https://開頭 server_names:其值爲一個主機名; arbitrary string:直接字符串,可以使用*通配符; regular expression:以~起始的正則表達式; 內置變量:$invalid_referer(所有不能符合valid_referer指定定義的引用請求均爲不合法引用) valid_referers none blocked server_names *.,magedu.com magedu.* www.magedu.com/galleries/ ~\.magedu\.; if ($invalid_referer) { return 403; }
6、ngx_http_ssl_module (實現http的加密)
ssl on|off 是否啓用SSL ssl_certificate file; 證書文件路徑; ssl_certificate_key file; 證書對應的私鑰文件; ssl_ciphers ciphers; 指明由nginx使用的加密算法,可以是OpenSSL庫中所支持各加密套件; ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]; //指明支持的ssl協議版本,默認爲後三個; ssl_session_cache off | none | [builtin[:size]] [shared:name:size]; //指明ssl會話緩存機制; off: 不使用session會話 none: 溫和禁止 builtin:使用OpenSSL內置的ssl會話緩存,對機制爲各worker私有; shared:在各worker之間使用一個共享的緩存; name 緩存空間的名稱 size:緩存空間的大小,字節爲單位,每1MB內存空間可緩存4000個會話 ssl_session_timeout time; //ssl會話超時時長;即ssl session cache中的緩存有效時長;默認5分鐘
示例:
server { listen 443; server_name localhost; ssl on; ssl_certificate /usr/local/nginx/conf/ssl/nginx.pem; ssl_certificate_key /usr/local/nginx/conf/ssl/nginx.key; ssl_session_timeout 5m; ssl_protocols SSLv2 SSLv3 TLSv1; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on; location / { root html; index index.html index.htm; } }
7、ngx_http_rewrite_module (將請求的url基於正則表達式進行重寫)
rewrite regex replacement [flag]; regex:正則表達式,用於匹配用戶請求的url; replacement:重寫爲的結果; [flag]: last:重寫完成之後停止對當前uri的進一步處理,改爲對其他location的url的新一輪處理; break:重寫完成之後停止對當前uri的處理,轉向其後面的其它配置; redirect:重寫完成之後會返回客戶端一個臨時的重定向,由客戶端對新的url重新發起請求(302); permanent:重寫完成之後會返回客戶端一個永久的重定向,由客戶端對新的url重新發起請求(301);
示例:所有請求http服務下admin的目錄的都重定向到https。
location /admin/ { rewrite /admin/.* redirect ; }
8、ngx_http_gzip_module (實現對響應報文的壓縮,節省資源和帶寬)
gzip on | off; 啓用或禁用gzip壓縮響應報文; gzip_comp_level level; 壓縮比,1-9,默認爲1; gzip_disable regex ...; regex是爲用於匹配客戶端響應器類型的正則表達式;表示對何種瀏覽器禁止使用壓縮功能; gzip_min_length length; 觸發壓縮功能的響應報文的最小長度; gzip_http_version 1.0 | 1.1; 設定啓用壓縮功能時,協議的最小版本; gzip_proxied off | expired | no-cache | no-store | private | no_last_modified | no_etag | auth | any ...; 定義對客戶端請求的具有何種請求屬性的資源啓用壓縮功能;如expired則表示對由於使用了expire首部而無法緩存的對象啓用壓縮功能; gzip_types mime-type ...; 指明僅對哪些類型的資源執行壓縮操作;即壓縮過濾器;默認爲txt/html
示例:
gzip on; gzip_http_version 1.0; gzip_comp_level 6; gzip_disable msie6; gzip_min_length 2; gzip_types text/plain text/css text/xml application/x-javascript application/xml application/json application/java-script;
9、ngx_http_fastcgi_module (實現fastcgi協議)
fastcgi_pass address; fastcgi監聽的地址 fastcgi_index name; 定義fastcgi應用的默認主頁 fastcgi_param parameter value [if_not_empty] 設定傳遞給後端fastcgi server參數及其值 fastcgi_cache_path path [levels=levels] keys_zone=name:size [inactive=time] [max_size=size]; 定義緩存:緩存空間等; 只能用於的上下文 :http path: 文件系統路徑,用於存儲緩存的文件數據 levels=#[:#[:#]] 緩存目錄層級定義 keys_zone=name:size 內存中用於緩存K/V映射關係的空間名稱及大小 name: cache的標識符; size: 元數據cache大小; inactive=time: 緩存的非活動的時間 max_size: 緩存空間上限; fastcgi_cache zone | off; 調用定義過的緩存; fastcgi_cache_key string; 定義要使用的緩存鍵 fastcgi_cache_methods GET | HEAD | POST ...; 爲請求方法對應的請求進行緩存,默認爲GET和HEAD; fastcgi_cache_min_uses number; 在指定時間內緩存項的最少使用次數 fastcgi_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_503 | http_403 | http_404 | off ...; 是否可使用過期的緩存項響應用戶請求; fastcgi_cache_valid [code ...] time; 對不同響應碼的響應設定其可緩存時長;
示例:
fastcgi_cache_path /var/cache/nginx levels=2:1 keys_zone=fscache:10m inactive=30 max_size=1G; //注意,這個不是定義在server中,而是定義在http中 location ~ \.php$ { root html; fastcgi_pass 172.18.250.77:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $fastcgi_script_name; include fastcgi_params; fastcgi_cache fscache; fastcgi_cache_key $request_uri; fastcgi_cache_min_users 1; fastcgi_cache_valid 200 302 10m; fastcgi_cacge_valid 403 5m; }
]# tree . 查看緩存的分級目錄 . ├── 9e │ └── 3 │ └── f46b8508aa08a6f8670fb088b8a9739e ├── eb │ └── f │ └── c86156f7dcfecf44876ca30d1bac7feb └── f1 └── a └── e251273eb74a8ee3f661a7af00915af1
10、ngx_http_proxy_module (反向代理模塊)
proxy_pass URL ;請求轉向的服務器 1、proxy_pass後面的路徑不帶URI時,其會將location的uri傳遞給 location /uri/ { proxy_pass 訪問後端主機時請求的是DocumentRoot目錄下的/uri/ } 2、location定義其uri時使用了正則表達模式匹配機制,則proxy_pass後的路徑必須不能使用uri; location ~|~* PATTERN { proxy_pass http://host; } 3、 proxy_pass後面路徑是一個uri時,會將location的uri替換爲proxy_pss後端主機的uri location /uri/ { proxy_pass http://host/new_uri/ 相當於/uri/映射爲後端主機的/new_uri } proxy_set_header field value; 設定向後端主機發送的請求報文的首部及其值 proxy_set_header X-Real-IP $remote_addr; 向後端主機傳遞客戶端IP proxy_cache_path path [levels=levels] keys_zone=name:size inactive=time [max_size=size]; //定義緩存代理 只能應用在http中 proxy_cache zone |off; 調用緩存 proxy_cache_key string; 定義緩存鍵 prox_cache_valid; 爲不同的狀態碼提供緩存 proxy_cache_use_stale error |timeout |invalid_header |updating 使用過期內容來響應客戶端,默認爲關閉 proxy_cache_purge sting 清理緩存 proxy_cache_methods 爲哪種請求方法緩存,默認爲get,head proxy_connect_timeout 與後端服務器建立連接的超時時長,默認爲60s,最長爲75s proxy_read_timeout 等待後端發送響應報文的超時時長,默認爲60s,兩次之間的時長 proxy_send_timeout 向後端服務器發送請求報文的超時時長,默認爲60S
]# tree . 代理緩存 . ├── 9e │ └── 3 │ └── f46b8508aa08a6f8670fb088b8a9739e ├── eb │ └── f │ └── c86156f7dcfecf44876ca30d1bac7feb └── f1 └── a └── e251273eb74a8ee3f661a7af00915af1
11、ngx_http_upstream_module (實現負載均衡)
1、 upstream name {...} 定義後端服務器組;引入新的上下文;只能用於http上下文 name:名稱,直接字符串 2、 server address [parameters] 定義服務器的地址和相關的參數; address格式: IP[:port] //給定IP地址 HOSTNAME[:port] //當後端有多個虛擬主機時,應該使用HOSTNAME unix:/path/to/some__sock_file [parameters]:參數 weight=number 服務器權重 max_fails=number 最大失敗嘗試次數 fail_timeout=time 設置多長時間後服務器不可用 backup 設置爲sorry server down 手動把服務器表示爲down,不在處理任何用戶請求;
示例:
upstream webserver { server 172.18.250.76:80 weight=1; server 172.18.250.77:80 weight=1; } location / { proxy_pass http://webserver; } ]# curl 172.18.250.75 //實現了負載均衡 Hello httpd ]# curl 172.18.250.75 Hello nginx ]# curl 172.18.250.75 Hello httpd ]# curl 172.18.250.75 Hello nginx
後端服務器的80端口down會自動把服務器剔除,服務起來也會自動加入繼續提供服務。
]# service httpd stop ]# curl 172.18.250.75 Hello nginx ]# curl 172.18.250.75 Hello nginx
ip_hash: 源地址哈希調度算法;只能用在upstream當中 upstream webserver { server 172.18.250.76:80 weight=1; server 172.18.250.77:80 weight=1; ip_hash; }
least_conn; 最少連接調度算法:考慮了後端服務器負載,用在upstream中 upstream webserver { server 172.18.250.76:80 weight=1; server 172.18.250.77:80 weight=1; least_conn;
keepalive connections; keepalive 32; 定義和後端主機的保持連接個數,一般和後端服務器數量一樣
health_check [parameters]: 定義後端主機的健康狀態檢測機制,只能用於location中 參數: interval=#:檢測的頻度,默認爲5秒 fails=number: 判定爲失敗的檢測次數,默認爲1 passes=number: 判定爲成功的檢測次數,默認爲1 uri=uri : 執行健康狀態檢測時的請求uri,默認請求主頁 match=name: 基於哪個match做檢測結果"成功"或者“失敗”的判斷 port=number: 向服務器的哪個端口發起健康狀態檢測請求,默認爲服務器自己的工作端口 match name {....} 僅能用於http上下文;對後端主機做健康狀態檢測時,定義其結果判斷標準 專用指令 status:期望的響應碼 status CODE status !CODE status CODE-CODE header ;基於響應首部進行判斷 header HEADER=VALUE header HEADER!=VALUE header [!]HEADER header HEADER ~ VALUE body: 期望的響應報文的主體部分應有的內容; body~ "BODY" body!~ "BODY"
注意:health_check和match name 兩個選項都是隻有商業版本的nginx纔會支持
hash key [consistent]; 定義調度方法,可自定義基於何種信息(key)進行綁定,用於upstream hash $remote_addr 根據客戶端IP hash $request_uri 根據請求的URI hash $cookie_username 根據客戶端的cookie