Nginx除了衆所周之的可以搭建很好的LNMP平臺外,它還提供了許多其他高級功能,如反向代理,url重寫等。現在就剖析Nginx的深層功能。
安裝nginx
- # yum -y install pcre-devel //nginx要用到的包
- # groupadd -r nginx
- # useradd -r -g nginx -s /sbin/nologin
- #tar xf nginx-1.0.14.tar.gz
- # ./configure \
- --prefix=/usr \
- --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/ \
- --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \
- --http-scgi-temp-path=/var/tmp/nginx/scgi \
- --with-pcre
- # make && make install
爲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
- #chmod +x /etc/rc.d/init.d/nginx
- #chkconfig --add nginx
- #chkconfig nginx on
- #service nginx start //啓動服務
一、Nginx---反向代理服務
所用有關服務器:
Nginx服務器:192.168.0.100
Web服務器: 192.168.0.11
在配置nginx反向代理服務之前,先說說什麼是反向代理。反向代理其實就是以代理服務器來接受Internet連接請求,然後,再把請求轉發給真正的服務器來響應。
- 編輯nginx服務器的配置文件
- location / {
- proxy_pass http://192.168.0.11 //代理服務器的地址
- }
在Web服務器上
- 首先安裝httpd提供Web服務
- #service httpd start
- #echo "<h1>192.168.0.11</h1>" > /var/www/html/index.html
此時訪問http://192.168.0.100,查看結果。
請求成功的轉發到了web服務器上。反向代理服務器工作正常。
二、爲反向代理啓用緩存功能
反向代理雖然保證了web服務器資源的安全性,但轉發過程卻降低了請求的響應速度。因此開啓緩存功能尤爲重要。下面通過兩組數據對比來展現緩存的優越性。以上述例子爲例。
在其他服務器上對http://192.168.0.100/index.html做壓力測試。
#ab -n 10000 -c 500 http://192.168.0.100
在開啓緩存服務前
每秒可平均處理152.17個請求,每個請求的平均響應時間約爲3.3s。
配置nginx反向代理的緩存功能
- 編輯nginx服務的配置文件
- http {
- proxy_cache_path /var/www/cache levels=1:2 keys_zone=mycache:20m
- max_size=2048m inactive=60m; levels:緩存級別 keys_zone保存了元數據,
- 名字爲mycache,大小爲20M 緩存數據最大爲2G
- proxy_temp_path /var/www/cache/tmp;
- ...
- location / {
- proxy_pass http://192.168.0.100/;
- proxy_cache mycache;
- proxy_cache_valid 200 302 60m;
- proxy_cache_valid 404 1m;
- }
- }
- #service nginx restart
此時再次測試網頁訪問壓力
此時的每秒可平均處理612.27個請求,每個請求的平均響應時間爲0.8s。對比可知緩存大大減少了響應時間。
三、反向代理多臺服務器實現負載均衡
實驗所需,此時再添加一臺Web服務器。地址爲:192.168.0.66
- #echo "<h1>192.168.0.66</h1>" > /var/www/html/index.html
在nginx服務上
- 編輯配置文件
- upstream cluster {
- server 192.168.0.11 weight=1;
- server 192.168.0.66 weight=2;
- }
- //使用upstream聲明一組可以被proxy_pass引用的服務器,weight指定權重,
- cluser是定義的名字
- server{
- listen 80;
- server_name localhost;
- location / {
- proxy_pass http://cluster;
- }
- }
- #service nginx restart
訪問服務:
輪詢響應成功。
四、URL重寫
url重寫使用的格式爲:rewrite regex replacement flag
rewrite是關鍵字,regex是需要重定向的內容,replacement是重定向後的格式,flag表示以什麼的方法重寫。
flag有四種格式:
last:匹配規則後再次對全部規則進行匹配
這種方法有時會產生死循環,如
rewrite ^/images/(.*\.jpg)$ http://192.168.0.100/images/$1 last
break:匹配後不再匹配後面的規則
redirect:臨時重定向標識,http協議代碼爲302
permanent:永久重定向標識,http協議代碼爲301
rewrite還支持if指令,用法爲:
if (condition) { ... }
條件可以是:
(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
在正則表達式中,可以使用圓括號標記匹配到的字符串,並可以分別使用$1,$2,...,$9進行引用
還是以例子說明吧。
如果用戶請求的頁面不存在,實現自定義跳轉。
- 編輯nginx配置文件
- location / {
- root html;
- index index.html index.htm;
- if (!-f $request_filename) {
- rewrite ^(/.*)$ /error.html permanent;
- }
- #echo "ERROR" > /usr/html/error.html
- #service nginx restart
此時在瀏覽中輸入一個不存在網頁,如:http://192.168.0.100/aa.html
此時服務器自動跳轉到了error.html頁面上。url重寫成功。
那麼我們如何將訪問forum站點的請求重定向到bbs站點上呢?
- 編輯配置文件
- location / {
- root html;
- index index.html index.htm;
- rewrite ^/forum/(.*)$ http://bbs/$1 last;
- }
- #cd /usr/html
- #mkdir bbs
- #cd bbs
- #vim index.html
- This is BBS page
- #service nginx restart
訪問http://192.168.0.100/forum/
訪問頁面爲bbs站點的內容,url重寫成功。
五、安裝配置第三方模塊,實現upstream中對後端http server的健康狀態檢測
要實現此功能需額外的功能模塊對nginx打補丁。
下載地址:https://github.com/cep21/healthcheck_nginx_upstreams,模塊名稱爲ngx_http_healthcheck_module
在此使用的模塊爲healthcheck_nginx_upstreams.zip。須注意的是此模塊適用於nginx的1.0版本,若nginx版本過高則需要其他的模塊。
- #unzip healthcheck_nginx_upstreams.zip
- 解壓後的文件爲cep21-healthcheck_nginx_upstreams-16d6ae7
- #mv cep21-healthcheck_nginx_upstreams-16d6ae7 health
- # tar xf nginx-1.0.14.tar.gz
- # cd nginx-1.0.14
- # patch -p1 < /root/health/nginx.patch //對nginx大補丁
- #./configure \ //重新編譯nginx
- --prefix=/usr \
- --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 \
- --add-module=/root/nginx/health //添加選項
- # make && make install
編輯配置文件
- upstream cluster {
- server 192.168.0.11 weight=1; //集羣服務器
- server 192.168.0.66 weight=2;
- healthcheck_enabled; //啓用檢查功能
- healthcheck_delay 1000;//檢查節點的間隔
- healthcheck_timeout 1000;//超時時間
- healthcheck_failcount 3;//允許的檢查失敗的次數
- healthcheck_send "GET /.health.html HTTP/1.0"; //檢查頁面
- }
- server {
- listen 80;
- server_name localhost;
- location / {
- proxy_pass http://cluster;
- }
- location /status { //顯示後端服務器狀態
- healthcheck_status;
- }
- }
- #service nginx start
- 在192.168.0.11服務器上
- #echo "OK" > /var/www/html/.health.html
- 在192.168.0.66 #echo "OK" > /var/www/html/.health.html
訪問頁面http://192.168.0.100發現輪詢服務正常。打開http://192.168.0.100/status
狀態顯示兩服務器工作正常。
在192.168.0.11上執行service httpd stop停止Web服務。再次刷新頁面:
狀態發生改變。而且此時訪問http://192.168.0.100會發現頁面只能定義在66節點上。
此時從新啓動192.168.0.11的Web服務,一切又恢復正常。
至此,nginx的高級功能介紹完畢。