Nginx(發音同 engine x)是一款輕量級的Web 服務器/反向代理服務器及電子郵件(IMAP/POP3)代理服務器,並在一個BSD-like 協議下發行。由俄羅斯的程序設計師Igor Sysoev所開發,最初供俄國大型的入口網站及搜尋引擎Rambler使用。其特點是佔有內存少,併發能力強,事實上nginx的併發能力確實在同類型的網頁伺服器中表現較好。
一、安裝nginx
1. 添加nginx用戶
[root@web ~]# groupadd -r nginx [root@web ~]# useradd -r -M -s /sbin/nologin -g nginx nginx
2. 安裝nginx
[root@web ~]# tar xf nginx-1.4.6.tar.gz [root@web ~]# cd nginx-1.4.6 [root@web nginx-1.4.6]# ./configure --prefix=/usr/local/ \ --sbin-path=/usr/sbin/nginx \ --conf-path=/etc/nginx/nginx.conf \ --error-log-path=/var/log/nginx/error.log \ --http-log-path=/var/log/nginx/access.log \ --pid-path=/var/run/nginx/nginx.pid \ --lock-path=/var/lock/nginx.lock \ --user=nginx \ --group=nginx \ --with-http_ssl_module \ --with-http_flv_module \ --with-http_stub_status_module \ --with-http_gzip_static_module \ --http-client-body-temp-path=/var/tmp/nginx/client/ \ --http-proxy-temp-path=/var/tmp/nginx/proxy/ \ --http-fastcgi-temp-path=/var/tmp/nginx/fcgi/ \ --with-pcre=/root/pcre-8.32 [root@web nginx-1.4.6]# make && make install
3. 爲nginx添加啓動腳本
#!/bin/sh # # nginx - this script starts and stops the nginx daemon # # chkconfig: - 85 15 # description: Nginx is an HTTP(S) server, HTTP(S) reverse \ # proxy and IMAP/POP3 proxy server # processname: nginx # config: /etc/nginx/nginx.conf # config: /etc/sysconfig/nginx # pidfile: /var/run/nginx.pid # Source function library. . /etc/rc.d/init.d/functions # Source networking configuration. . /etc/sysconfig/network # Check that networking is up. [ "$NETWORKING" = "no" ] && exit 0 nginx="/usr/sbin/nginx" prog=$(basename $nginx) NGINX_CONF_FILE="/etc/nginx/nginx.conf" [ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx lockfile=/var/lock/subsys/nginx make_dirs() { # make required directories user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -` options=`$nginx -V 2>&1 | grep 'configure arguments:'` for opt in $options; do if [ `echo $opt | grep '.*-temp-path'` ]; then value=`echo $opt | cut -d "=" -f 2` if [ ! -d "$value" ]; then # echo "creating" $value mkdir -p $value && chown -R $user $value fi fi done } start() { [ -x $nginx ] || exit 5 [ -f $NGINX_CONF_FILE ] || exit 6 make_dirs echo -n $"Starting $prog: " daemon $nginx -c $NGINX_CONF_FILE retval=$? echo [ $retval -eq 0 ] && touch $lockfile return $retval } stop() { echo -n $"Stopping $prog: " killproc $prog -QUIT retval=$? echo [ $retval -eq 0 ] && rm -f $lockfile return $retval } restart() { configtest || return $? stop sleep 1 start } reload() { configtest || return $? echo -n $"Reloading $prog: " killproc $nginx -HUP RETVAL=$? echo } force_reload() { restart } configtest() { $nginx -t -c $NGINX_CONF_FILE } rh_status() { status $prog } rh_status_q() { rh_status >/dev/null 2>&1 } case "$1" in start) rh_status_q && exit 0 $1 ;; stop) rh_status_q || exit 0 $1 ;; restart|configtest) $1 ;; reload) rh_status_q || exit 7 $1 ;; force-reload) force_reload ;; status) rh_status ;; condrestart|try-restart) rh_status_q || exit 0 ;; *) echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}" exit 2 esac
4. 簡單配置和啓動
[root@web ~]# vim /etc/nginx/nginx.conf user nginx; pid /var/run/nginx.pid; [root@web ~]# service nginx restart nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful Stopping nginx: [ OK ] Starting nginx: [ OK ]
二. 配置nginx
1) location
語法規則: location [=|~|~*|^~] /uri/ { … }
= | 表示精確匹配,不會去匹配子目錄下的文件 |
~ | 表示區分大小寫的正則匹配 |
~* | 表示不區分大小寫的正則匹配 |
^~ | 表示不做正則表達式匹配 |
/ | 表示通用匹配,任何請求都會匹配到 |
2) root
語法規則:root PATH (可以用在http、server、location中)
root用來指定網站的根目錄
3)alias
語法規則:alias file-path|directory-path
alias的普通用法:
location /alias/test.html {
alias /web/alias/test.html;
}
使用正則表達式的alias:
location ~ ^/test/(.*)$ {
alias /var/nginx/test/$1;
}
如果root在/var/www/html下,而訪問http://domain/alias/test.html這個目錄時,就會訪問web下alias/test.html
root和alias的區別:
root指定的目錄就是location後面的“/”,而alias指定的目錄需要包括location後面的路徑,如上面的例子。
4) index
語法規則:index index.html index.htm; #指定主頁文件
autoindex on; #索引功能打開,當沒有找到定義的主頁文件時,就會把網站跟目錄下的文件都列出來
5) 基於主機的訪問控制
allow [ address | CIDR | all ]
deny [ address | CIDR | all ]
例子:
location / {
root /var/www/html;
index index.html index.htm;
allow 192.168.2.0/24;
deny all;
}
6) 定義虛擬主機
server { listen 80 default; server_name _; location / { root /var/nginx/test; index index.html; } } server { listen 80; server_name www.aa.com; location / { root /var/www/html; index index.html index.htm; } } #定義了2個虛擬主機,上面一個是默認虛擬主機
7) 基於用戶認證的nginx監控
[root@web ~]# htpasswd -m -c /etc/nginx/.htpasswd maria [root@web ~]# vim /etc/nginx/nginx.conf location /nginx_status { stub_status on; #打開監控功能 access_log off; #關閉日誌 auth_basic "who are you?"; #認證時的提示信息 auth_basic_user_file /etc/nginx/.htpasswd; #認證的文件 } #在編譯時需添加--with-http_stub_status_module這個模塊,纔可以開啓監控
8)URL重寫
語法規則: rewrite regex replacement flag
flag的種類:
last | 把當前的重寫指令執行結束,並且重新啓動匹配進程,一般都是用last |
break | 中止Rewirte,不在繼續匹配 |
redirect | 返回臨時重定向的HTTP狀態302 |
permanent | 返回永久重定向的HTTP狀態301 |
統一資源定位符(URL)和統一資源標識符(URI):
www.aa.com/nginx/a.html,對於這個地址,可以理解爲這個地址就是一個URL,/nignx/a.html就是URI。就相當於一個絕對路徑,一個相對路徑。
例子:
http://www.aa.com/maria.php?id=123 #用戶請求的地址
http://www.aa.com/123/maria #重寫後的地址
rewrite ^/(maria)\.php\?id=(.*)$ /$2/$1 last; #書寫方法,前面匹配的就是URI
9)if語句
語法規則: if (condition) { ... }
應用環境: server, location
congdition:
1、變量名; false values are: empty string ("", or any string starting with "0";)
2、對於變量進行的比較表達式,可使用=或!=進行測試;
3、正則表達式的模式匹配:
~ 區分大小的模式匹配
~* 不區分字母大小寫的模式匹配
!~ 和 !~* 分別對上面的兩種測試取反
4、測試文件是否存在-f或!-f
5、測試目錄是否存在-d或!-d
6、測試目錄、文件或鏈接文件的存在性-e或!-e
7、檢查一個文件的執行權限-x或!-x
簡單應用:
#實現域名跳轉 server { listen 80; server_name jump.aa.com; index index.html index.php; root /var/www/html; rewrite ^/ http://www.aa.com/; }
#簡單的防盜鏈配置: location ~* \.(gif|jpg|png|swf|flv)$ { valid_referers none blocked www.aa.com; if ($invalid_referer) { rewrite ^/ http://www.aa.com/403.html; # return 404 } }
10) 日誌管理
語法規則: log_format name format
Ⅰ、設定錯誤日誌格式及級別:
http { log_format my_log_fm '$http_x_forwarded_for - $remote_user [$time_local]' '"$request" $status $body_bytes_sent' '"$http_referer" "$http_user_agent"'; access_log /var/log/nginx/access.log my_log_fm; error_log /var/log/nginx/error.log warn; }
$http_x_forwarded_for
和$remote_user用於記錄客戶端網關的IP地址和用戶
$time_local用於記錄訪問時間和時區
$request用於記錄請求的URL和http協議
$status用於記錄請求的狀態,例如請求成功時狀態碼爲200
$body_bytes_sent用於記錄發送給客戶端文件主體的內容大小
$http_referer用戶記錄請求是從哪個頁面連接訪問過來的
$http_user_agent用戶記錄客戶端瀏覽器的相關信息
Ⅱ、記錄類似apache格式的日誌:
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 /var/log/nginx/access.log main;
Ⅲ、啓用日誌緩存:
open_log_file_cache max=100 inactive=30s min_uses=2 valid=1m;
max | 最多在緩存中最大文件描述符的數量 |
inactive | 在固定時間內沒有被訪問過的文件描述符,就從緩存中移除 |
min_uses | 在inactive的時間內,被訪問的最少次數,滿足這個次數才放到緩存中 |
vaild | 檢查緩存中的日誌在磁盤上是否還存在,m表示分鐘 |
off | 關閉日誌緩存功能 |
Ⅳ、日誌切割
nginx的日誌文件沒有rotate功能。如果你不處理,日誌文件將變得越來越大,可以用腳本+crontab來進行日誌切割。
[root@web ~]# vim log_switch.sh #!/bin/bash # logs_path="/var/log/nginx/" #當前日誌的存放目錄 mkdir -p ${logs_path}$(date -d"yesterday" +"%Y")/$(date -d"yesterday" +"%m") #在上面的目錄下,給日誌創建以時間命名的目錄 mv ${logs_path}aa.access.log ${logs_path}$(date -d"yesterday" +"%Y")/$(date -d"yesterday" +"%m")/$(date -d"yest erday" +"%Y%m%d").log #移動日誌到日期命名的目錄中 service nginx reload [root@web ~]# crontab -e 00 00 * * * /root/log_switch.sh
11. 設定限速
#爲某個特定路徑限速 server { server_name www.aa.com; location /downloads/ { limit_rate 256k; limit_rate_after 20m; root /var/www/html; } .. } #限制搜索引擎的速度 if ($http_user_agent ~ Google|Yahoo|MSN|baidu) { limit_rate 128k; }
limit_rate_after
20m表示下載的前20M不做限速
limit_rate限制速度爲256K/s
12. 爲反向代理啓用緩存功能
http { proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=STATIC:10m inactive=24h max_size=1g; server { location / { proxy_pass http://192.168.2.87; proxy_set_header Real-ip $remote_addr; proxy_cache STATIC; proxy_cache_valid 200 1d; #對響應碼爲200的文件,指定緩存失效的檢查時間 client_max_body_size 50m; client_body_buffer_size 256k; proxy_connect_timeout 30; proxy_send_timeout 30; proxy_read_timeout 60; proxy_buffer_size 256k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; proxy_temp_file_write_size 256k; proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504; } } }
levels 指定該緩存空間有兩層hash目錄,第一層目錄爲1個字母,第二層爲2個字母
keys_zone=STATIC:1m 參數用來爲這個緩存區起名(proxy_cache 指令需要用到其後對應緩存區名稱),:1m 指內存緩存空間大小爲1MB
inactive=24h指如果緩存數據在24小時(天:d、秒:s、分:m)內沒有被訪問,將自動被刪除
max_size=1g 指硬盤緩存大小爲1g
13. 負載均衡功能
upstream backend { server www.aa.com weight=5 down [backup]; server 127.0.0.1:8080 max_fails=3 fail_timeout=30s; server unix:/tmp/backend3; }
weight 設定權重,默認爲1
max_fails 在fail_timeout指令設定的時間內發往此server的不成功的請求次數,達到此數目後,此服務器將變爲不可操作狀態;默認值爲1;設定爲0值則禁用此功能;
fail_timeout 默認爲10秒;
down 列表中有這個服務器,但是不啓用它
backup 當其他負載均衡的服務器都掛了,纔會啓用backup