nginx反向代理

說明:共需要3臺虛擬機,202.207.178.6安裝nginx,作爲前端反向代理服務器,202.207.178.7和202.207.178.8作爲後端服務器安裝apache,提供web服務。


一、編譯安裝nginx

1、首先添加用戶nginx,實現以之運行nginx服務進程

# groupadd -r -g 108 nginx

# useradd -r -g 108 -u 108 nginx

2、將下載好的軟件包解壓並安裝(我這裏是nginx-1.4.7.tar.gz)

# tar xf nginx-1.4.7.tar.gz

# cd nginx-1.4.7

接着開始編譯和安裝:

# ./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 \

--with-file-aio

# make && make install

報錯時可能要求安裝如下包,按需安裝即可!

# yum -y install pcre-devel

# yum -y install gcc

# yum -y install openssl-devel

3、爲nginx提供SysV init腳本:


新建文件/etc/rc.d/init.d/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、而後爲此腳本賦予執行權限:

# chmod +x /etc/rc.d/init.d/nginx


5、添加至服務管理列表,並讓其開機自動啓動:

# chkconfig --add nginx

# chkconfig nginx on


6、而後就可以啓動服務並測試了:

# service nginx start

二、配置反向代理

1、在前端服務器上提供訪問頁:

# mkdir /usr/html/forum

# vim /usr/html/forum/index.html

添加以下內容,表明是在nginx上:

<h1>Forum ON Nginx</h1>

http://202.207.178.6/forum/ 可以訪問到此頁面!

2、在後端服務器上提供web服務配置(202.207.178.7)

# yum -y install httpd

# cd /var/www/html/

# mkdir bbs

# cd bbs/

# vim index.html

添加如下內容:

<h1>Forum ON Backserver<h1>

# service httpd start

代理方式一:

Nginx通過proxy模塊實現反向代理功能。在作爲web反向代理服務器時,nginx負責接

        收客戶請求,並能夠根據URI、客戶端參數或其它的處理邏輯將用戶請求調度至上游服

        務器上。nginx在實現反向代理功能時的最重要指令爲proxy_pass,它能夠將location

        定義的某URI代理至指定的上游服務器(組)上。如下面的示例中,location的/forum將

        被替換爲上游服務器上的/bbs

1)編輯前端服務器配置文件,添加反向代理相關內容,然後重啓nginx服務,即可開

          始測試

# vim /etc/nginx/nginx.conf

在server段中添加如下內容

location /forum {

proxy_pass http://202.207.178.7/bbs;

}

# nginx -t

# service nginx restart

2)訪問測試

此時訪問 http://202.207.178.6/forum/

瀏覽器中會顯示:Forum ON Backserver

代理方式二:

如果location的URI是通過模式匹配定義的,其URI將直接被傳遞至上游服務器,而不

        能爲其指定轉換的另一個URI

        例如下面示例中的/forum將被代理爲http://202.207.178.7/forum。

1)編輯前端服務器配置文件,添加反向代理相關內容,然後重啓nginx服務,在前端

         服務器上更改bbs爲forum,即可開始測試

        # vim /etc/nginx/nginx.conf

在server段中添加如下內容

   location ~* /forum {

proxy_pass http://202.207.178.7;

}

# nginx -t

# service nginx restart

2)後端(202.207.178.7):

# mv bbs/ forum

3、使後端服務器能夠記錄客戶端地址,而不是前端nginx地址

前端:

# vim /etc/nginx/nginx.conf

在此前定義的location中增加以下內容,以使客戶端IP傳送到後端服務器:

proxy_set_header X-Real-IP $remote_addr;

# service nginx restart

後端(202.207.178.7):

# vim /etc/httpd/conf/httpd.conf

將日誌格式改爲以下內容:

LogFormat "%{X-Real-IP}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

# service httpd restart

# tail /etc/httpd/logs/access_log

此時進行訪問測試即可看到記錄了客戶端地址

4、將所有訪問代理至後端:

註釋掉原來的根

#location / {

#   root   html;

#    index  index.html index.htm;

#}

將自己定義的location改爲根

location / {

proxy_pass http://202.207.178.7;

proxy_set_header X-Real-IP $remote_addr;

}

測試:http://202.207.178.6 即可發現訪問到後端主機

5、使用Upstream實現對後端服務器的負載均衡(node1:202.207.178.7和             node2:202.207.178.8),並實現健康狀況檢查

說明:Nginx支持3種輪調算法:

round-robin:加權輪調(默認)

ip-hash:源地址哈希

least_conn:當前最少連接數

node1:

# vim /var/www/html/index.html

<h1>node1</node>

重啓httpd服務

node2:

# vim /var/www/html/index.html

<h1>node2</node>

重啓httpd服務

前端nginx:

# vim /etc/nginx/nginx.conf

此項必須在server段之外定義:

#max_fails=2 檢查時最多允許錯誤次數

#fail_timeout=2 檢查是否錯誤持續幾秒

upstream webservers {

server 202.207.178.7 weight=1 max_fails=2 fail_timeout=2;

server 202.207.178.8 weight=1 max_fails=2 fail_timeout=2;

server 127.0.0.1:8080 backup;

}


location / {

proxy_pass http://webservers/;

proxy_set_header X-Real-IP $remote_addr;

}

定義錯誤頁:

server {

listen 8080;

server_name localhost;

root /web/errorpages;

index index.html;

}

# mkdir -pv /web/errorpages

# vim /web/errorpages/index.html

sorry.........

此時便可重啓nginx服務,訪問:http://202.207.178.6,進行訪問測試了!

6、在nginx本地使用緩存(使用proxy_cache_path不能定義在server中)

proxy_cache_path:

path:定義磁盤位置

levels=levels :定義緩存目錄的子目錄級別(包括目錄級別及每級字符個

                    數,最多允許定義3級子目錄)

keys_zone :用來存儲鍵的區域

max_size: 定義磁盤空間大小(需要cache_manager模塊根據LRU算法做頁面

                 調度)

另外常用的3種緩存:

open_log_cache:日誌緩存

open_file_cache:打開文件緩存

fastcgi_cache:fastcgi緩存

定義緩存:(前端)

# vim /etc/nginx/nginx.conf

proxy_cache_path /nginx/cache/first levels=1:2 keys_zone=first:20m max_size=1g;

   location / {

                proxy_pass http://webservers/;

                proxy_set_header X-Real-IP $remote_addr;

                proxy_cache first; #必須在server中啓用此項,以說明使用緩存功能

proxy_cache_valid 200 10m; #表明對200這樣的正確頁緩存10分鐘         }

# mkdir -pv /nginx/cache/first

# nginx -t

# service nginx restart

現在即可開始測試了!


至此,nginx常用的反向代理功能配置完畢!

                                   歡迎批評指正!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章