標籤:nginx
nginx
Nginx(engine X) 是一個高效能的 HTTP 伺服器和反向 Proxy伺服器,這款軟體開發的目的是為瞭解決 C10k 問題。
Nginx 的架構利用了許多現代作業系統的特性,以實現一個高效能的 HTTP 伺服器。例如在 Linux 系統上,Nginx 使用了 epoll,sendfile,File AIO,DIRECTIO 等機制,使得 Nginx 不僅效能高效,而且資源佔用率非常低,官方宣稱 nginx 維持 10000 個非活動的 HTTP keep-alive 串連僅需要 2.5M 記憶體。
Nginx會按需同時運行多個進程:一個主進程(master)和幾個背景工作處理序(worker),配置了緩衝時還會有緩衝載入器進程(cache loader)和緩衝管理器進程(cache manager)等。所有進程均是僅含有一個線程,並主要通過“共用記憶體”的機制實現處理序間通訊。主進程以 root 使用者身份運行,而worker、cache loader 和 cache manager 均應以非特權使用者身份運行。
系統平台:CentOS release 6.6 (Final) 64位。
一、安裝編譯工具及庫檔案
yum -y install make zlib zlib-devel gcc-c++ libtool openssl openssl-devel
二、首先要安裝 PCRE
PCRE 作用是讓 Ngnix 支援 Rewrite 功能。
1、下載 PCRE 安裝包
[[email protected] ~]# wget http://downloads.sourceforge.net/project/pcre/pcre/8.35/pcre-8.35.tar.gz
2、解壓,進入安裝包目錄
[[email protected] ~]# tar xf pcre-8.35.tar.gz
[[email protected] ~]# cd pcre-8.35
3、編譯安裝
[[email protected] pcre-8.35]# ./configure && make && make install
4、查看pcre版本
[[email protected] pcre-8.35]# pcre-config --version
8.35
三、安裝nginx
1、下載nginx安裝包
[[email protected] ~]# wget http://nginx.org/download/nginx-1.9.5.tar.gz
2、解壓,進入安裝包目錄
[[email protected] ~]# tar xf nginx-1.9.5.tar.gz
[[email protected] ~]# cd nginx-1.9.5
3、建立 nginx 運行使用的使用者
[[email protected] nginx-1.9.5]# /usr/sbin/groupadd nginx
[[email protected] nginx-1.9.5]# useradd -g nginx nginx
4、編譯安裝
常用編譯參數
--prefix=PATH:指定 nginx 的安裝目錄
--conf-path=PATH:指定 nginx.conf 設定檔路徑
--user=NAME:nginx 背景工作處理序的使用者
--with-pcre:開啟 PCRE Regex的支援
--with-http_ssl_module:啟動 SSL 的支援
--with-http_stub_status_module:用於監控 Nginx 的狀態
--with-http-realip_module:允許改變用戶端要求標頭中用戶端 IP 位址
--with-file-aio:啟用 File AIO
--add-module=PATH:添加第三方外部模組
這裡提供一個完整的編譯方案:
[[email protected] nginx-1.9.5]# ./configure --prefix=/usr/local/nginx \
--conf-path=/usr/local/nginx/conf/nginx.conf \
--error-log-path=/usr/local/nginx/log/error.log \
--http-log-path=/usr/local/nginx/log/access.log \
--http-client-body-temp-path=/usr/local/nginx/client_body \
--http-proxy-temp-path=/usr/local/nginx/proxy \
--http-fastcgi-temp-path=/usr/local/nginx/fastcgi \
--http-uwsgi-temp-path=/usr/local/nginx/uwsgi \
--pid-path=/usr/local/nginx/log/nginx.pid \
--lock-path=/usr/local/nginx/log/nginx \
--user=nginx \
--group=nginx \
--with-file-aio \
--with-http_ssl_module \
--with-http_realip_module \
--with-http_sub_module \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--with-pcre
[[email protected] nginx-1.9.5]# make && make install
5、查看nginx版本
[[email protected] nginx-1.9.5]# /usr/local/nginx/sbin/nginx -v
nginx version: nginx/1.9.5
注意:在這可能會報錯
/usr/local/nginx/sbin/nginx: error while loading shared libraries: libpcre.so.1: cannot open shared object file: No such file or directory
這是因為缺少庫檔案,確認安裝好pcre軟體(nginx 依賴該軟體),建立軟串連即可
[[email protected] nginx-1.9.5]# ls /lib/ |grep pcre
[[email protected] nginx-1.9.5]# ls /lib64/ |grep pcre
libpcre.so.0
libpcre.so.0.0.1
[[email protected] nginx-1.9.5]# ln -s /lib64/libpcre.so.0.0.1 /lib64/libpcre.so.1
6、啟動和關閉
檢查設定檔ngnix.conf的正確性命令:
# /usr/local/nginx/sbin/nginx -t
啟動 nginx:
# nginx -c /etc/nginx/nginx.conf
關閉 nginx
# nginx -s stop
重讀設定檔
# nginx -s reload
# pkill -HUP nginx
重新開啟記錄檔
# nginx -s reopen
# pkill -USR1 nginx
四、nginx.conf 設定檔
Nginx 設定檔主要分成四部分:main(全域設定)、http(HTTP 的通用設定)、server(虛擬機器主機設定)、location(匹配 URL 路徑)。還有一些其他的配置段,如 event,upstream 等。
1、通用設定
user nginx
指定運行 nginx workre 進程的使用者和組
worker_rlimit_nofile #
指定所有 worker 進程能夠開啟的最大檔案數
worker_cpu_affinity
設定 worker 進程的 CPU 粘性,以避免進程在 CPU 間切換帶來的效能消耗。如 worker_cpu_affinity 0001 0010 0100 1000;(四核)
worker_processes 4
worker 背景工作處理序的個數,這個值可以設定為與 CPU 數量相同,如果開啟了 SSL 和 Gzip,那麼可以適當增加此數值
worker_connections 1000
單個 worker 進程能接受的最大並發串連數,放在 event 段中
error_log logs/error.log info
錯誤記錄檔的存放路徑和記錄層級
use epoll
使用 epoll 事件模型,放在 event 段中
2、http 伺服器
server {}:
定義一個虛擬機器主機
listen 80;
定義監聽的地址和連接埠,預設監聽在本機所有地址上
server_name NAME [...];
定義虛擬機器主機名,可以使用多個名稱,還可以使用Regex或萬用字元。
sendfile on
開啟 sendfile 調用來快速的響應用戶端
keepalive_timeout 65
長連線逾時時間,單位是秒。
send_timeout
指定響應用戶端的逾時時間
client_max_body_size 10m
允許用戶端請求的實體最大大小
root PATH
佈建要求 URL 所對應資源所在檔案系統上的根目錄
location [ = | ~ | ~* | ^~ ] URI { ... }
設定一個 URI 匹配路徑
=:精確匹配
~:Regex匹配,區分字元大小寫
~*:Regex匹配,不區分字元大小寫
^~:URI 的前半部分匹配,且不實用Regex
優先順序:
= > location 完整路徑 > ^~ > ~ > ~* > location 起始路徑 > location /
allow 和 deny
基於 IP 存取控制,如:
僅允許 192.168.0.0/24 網段用戶端訪問
allow 192.168.0.0/24;
deny all;
stub_status on
開啟狀態顯式,僅能用於 location 中:
開啟狀態顯式頁面
location /status {
stub_status on;
allow 172.16.0.0/16;
deny all;
}
rewrite <REGEX> <REPL> <FLAG>
URL 重寫,可以使用多種標記
例如:
rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
可用的 flag:
- last:重寫完成後,繼續匹配其他 rewrite 規則
- break:重寫完成後不再繼續匹配
- redirect:返回 302 重新導向(臨時重新導向),用戶端對重新導向的 URL 發起新的請求
- permanent:返回 301 重新導向(永久重新導向),用戶端對重新導向的 URL 發起新的請求
一個 server 配置樣本:
server {
listen 80;
server_name localhost;
root /web/htdocs;
location / {
index index.html index.htm;
}
location /status {
stub_status on;
allow 10.0.0.0/8;
deny all;
access_log off;
}
3、SSL 的配置
啟用一個 SSL 虛擬機器主機
server {
listen 443;
server_name example.com;
root /apps/www;
index index.html index.htm;
ssl on;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
# ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
# ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
# ssl_prefer_server_ciphers on;
}
其中 ssl_certificate 表示 CA 檔案,ssl_certificate_key 表示密鑰檔案。
如果想把 http 請求強制轉到 https,可以這樣:
server {
listen 80;
server_name example.me;
return 301 https://$server_name$request_uri;
}
4、nginx 做負載平衡反向 Proxy
nginx 做反向 Proxy時,後端主機有多台,可以使用 upstream 定義一個後端主機池,在反向 Proxy時直接使用主機池的名字。在 upstream 中可以定義負載平衡調度演算法,權重,健康狀態檢測等參數。
例如:
upstream backend {
server 172.16.0.1:80 weight=1 max-fails=3 fail_timeout=10;
server 172.16.0.2:80 weight=1max-fails=3 fail_timeout=10;;
}
預設請求下,使用 round-robin 調度演算法,並有健康狀態檢查和恢複主機的能力。
ningx 還可以使用這些演算法:
ip_hash:基於源地址雜湊,主要目的是會話保持
least_conn:基於最少活動串連進行調度
sticky:基於 cookie 進行會話綁定,nginx 會在用戶端第一次訪問時插入路由資訊到 cookie 中,或者選擇 cookie 中的某個欄位的值作為鍵,以後每次請求將基於此資訊進行調度
基於 cookie 的會話綁定共有 cookie,route 和 learn 三種。
例如,基於 cookie name 的調度:
upstream backend {
server backend1.example.com;
server backend2.example.com;
sticky cookie srv_id expires=1h domain=.example.com path=/;
}
使用此主機群組進行反向 Proxy:
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_haeder X-Forwared-For $proxy_add_x_forwarded_for;
}
proxy_pass URL 指定代理的後端主機,可以指定 "http" 或 "https" 協議,網域名稱可以是 ip 地址,也可以是 upstream 池名字
如果代理指定的是一個 URI 地址,如 http://127.0.0.1/remote,那麼將直接被代理至指定 URI,無論請求的 URI 是什麼
如果代理指定的一個主機而沒有 URI,如 http://127.0.0.1,用戶端請求的URI將被傳遞至指定網域名稱
如果 location 中使用模式比對 url,那麼 url 也會被傳遞至代理 URL 的末端
如果 location 中使用了 URI 重寫,那麼 proxy_pass 會使用重寫後的結果進行處理
proxy_set_header HEADER VALUE 對轉寄的報文首部進行修改
5、反向 Proxy時的緩衝相關設定
proxy_cache_path PATH [levels=levels] keys_zone=NAME:SIZE
定義磁碟緩衝路徑,nignx 的緩衝是以索引值方式存放的,keys_zone 用於指定鍵存放的記憶體空間名字和大小,對應的值則存放在 PATH 指定的路徑中。levels 可以指定緩衝存放路徑的級數和名稱字元數。此設定只能在 http 段中定義。
如:
proxy_cache_path /var/cache/nginx/proxy levels=1:2 keys_zone=one:10m;
proxy_cache_valid [code ...] time 指定不同響應碼的內容的緩衝時間
如:
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_valid any 1m;
proxy_cache_method METHOD 定義哪些方法的請求結果可以被緩衝,如:
proxy_cache_method GET;
proxy_cache_method HEAD;
proxy_cache NAME 指定使用預先定義的緩衝空間用於緩衝
6、 fastCGI 代理的設定
使用 fastCGI 時,設定代理的方法同 porxy_pass 類似,同時還可以使用 fastCGI 緩衝,設定的方法也和 proxy_cache 類似。
location ~ \.php$ {
root /web/htdocs;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
7、一些常用內建變數
$arg_name:請求 uri 中的 name 參數至
$args:請求 uri 的所有參數,和 $query_string 相同
$uri:當前請求的 uri,不帶參數
$request_uri:請求的 uri,帶完整參數
$host:http 請求報文中 host 首部,如果沒有 host 首部,則以處理此請求的虛擬機器主機的主機名稱替代
$hostname:nginx 服務運行在主機的主機名稱
$remote_addr:用戶端 IP
$remote_port:用戶端 port
$remote_user:使用使用者認證時用戶端使用者輸入的使用者名稱
$request_filename:使用者請求中的 URI 經過本地 root 或 alias 轉換後映射的本地的檔案路徑
$request_method:要求方法
$server_addr:伺服器位址
$server_name:伺服器名稱
$server_port:伺服器連接埠
$server_protocol:伺服器向用戶端發送響應時的協議,如 http/1.1,http/1.0
$scheme:在請求中使用的 scheme,如 https://www.baidu.com/ 中的 https
$http_name:匹配請求報文中的指定 HEADER,如 $http_host 匹配請求報文中的 host 首部
$sent_http_name:匹配響應報文中指定的 HEADER,例如 $sent_content_type 匹配響應報文中的 content-type 首部
$status:響應狀態
Nginx中文參考文檔
http://tool.oschina.net/apidocs/apidoc?api=nginx-zh
Nginx配置與應用詳解
http://developer.51cto.com/art/201004/194472.htm
Nginx開發從入門到精通
http://tengine.taobao.org/book/index.html
本文出自 “baby神” 部落格,請務必保留此出處http://babyshen.blog.51cto.com/8405584/1881485
Nginx伺服器搭建和基本配置詳解