天天看點

Nginx進階應用--負載均衡、rewrite規則

Nginx除了可以用作web伺服器外,他還可以用來做高性能的反向代理伺服器,它能提供穩定高效的負載均衡解決方案。nginx可以用輪詢、IP哈希、URL哈希等方式排程後端伺服器,同時也能提供健康檢查功能。目前有衆多公司均已經部署使用nginx實作基于七層的負載均衡功能。

一、 Nginx負載均衡

為了實作Nginx的反向代理以及負載均衡功能,應用中需要用到兩個子產品,HttpProxyModule和HttpUpstreamModule子產品;其中HttpProxyModule子產品的作用是将使用者的資料請求轉發到其他伺服器上,HttpUpstreamModule子產品是提供負載均衡技術。

Nginx目前提供的負載均衡算法:

ngx_http_upstream_round_robin,權重輪詢,可均分請求,是預設算法,內建在架構中。

ngx_http_upstream_ip_hash_module,IP哈希,可保持會話。

ngx_http_upstream_least_conn_module,最少連接配接數,可均分連接配接。

ngx_http_upstream_hash_module,一緻性哈希,可減少緩存資料的失效

負載均衡實作原理拓撲圖(多層負載)

Nginx反向代理子產品配置方法示例解析

示例:

location ~* \.(mp3|mp4)$ {        #比對URL以MP3或者MP4結尾的請求

    proxy_pass http://localhost:8080        #轉發到本機8080端口

}

location / {                                    #比對任意URL

    proxy_pass http://localhost:8081  #轉發到本機8081端口

        proxy_set_header    X-Forwarded-For    $remote_addr    #保留使用者真實IP

location指令可以直接比對字元串,也可以進行正規表達式比對

~表示區分大小寫,~*表示不區分大小寫比對,=表示精确比對

proxy_pass指令可以根據location比對的情況建立前後端的代理映射關系

X-Forwarded-For用于實作定義資料標頭,記錄使用者真實IP

Nginx負載均衡子產品配置方法示例解析

http {

upstream backend {

ip_hash;

server web1.test.com weight 1;

server web2.test.com weight 2;

server web3.test.com ;

server {

listen 80;

server_name web.test.com;

location / {

proxy_pass http://backend;

}}}

upstream定義後端伺服器集合,backend是伺服器組名

proxy-pass和fastcgi_pass将請求轉發給一組伺服器

ip_hash可以根據使用者ip位址的hash值配置設定固定的後端伺服器

二、 Nginx負載均衡案例

伺服器名稱

網路配置

nginx.test.com

eth0:122.126.152.183

eth1:192.168.1.2

web1.test.com

eht0:192.168.1.3

web2.test.com

eth0:192.168.1.4

web3.test.com

eth0:192.168.1.5

3台web機器配置

在web1 web2 web3上安裝httpd并配置網卡

vim /etc/sysconfig/network-scripts/ifcfg-eth0

DEVICE=eth0

BOOTPROTO=static

IPADDR=192.168.1.3

NETMASK=255.255.255.0

GATEWAY=192.168.1.2

ONBOOT=yes

TYPE=Ethernet

service network restart

yum install -y httpd

iptables -F

iptables -X

service iptables save

setenforce 0

sed -i s/enforcing/disabled/g /etc/sysconfig/selinux

echo "web1  192.168.1.3" > /var/www/html/index.html

service httpd restart

chkconfig httpd on

web2 web3機器上執行與web1相同步驟,注意修改部分參數

Nginx代理伺服器設定 

IPADDR=122.126.152.183

GATEWAY=122.126.152.0

vim /etc/sysconfig/network-scripts/ifcfg-eth1

DEVICE=eth1

IPADDR=192.168.1.2

GATEWAY=192.168.1.1

wget http://nginx.org/download/nginx-1.6.3.tar.gz

tar zxf nginx-1.6.3.tar.gz -C /usr/src/

yum install gcc pcre pcre-devel openssl openssl-devel gd gd-devel perl perl-ExtUtils-Embed

cd /usr/src/nginx-1.6.3/

./configure --prefix=/usr/local/nginx \

--with-ipv6 \

--with-http_ssl_module \

--with-http_realip_module \

--with-http_addition_module \

--with-http_dav_module \

--with-http_gzip_static_module \

--with-http_perl_module \

--with-mail_ssl_module

make && make install

修改配置檔案

vim /usr/local/nginx/conf/nginx.conf

user    nobody;

worker_processes    1;

error_log    logs/error.log    notice;

pid    logs/nginx.pid;

events    {

worker_connections    5024;

http    {

include    mime.types;

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" ';

sendfile    on;

tcp_nopush    on;

server_tokens    off;

keepalive_timeout    65;

keepalive_requests    100;

gzip    on;                                    #開啟壓縮

gzip_min_length    1000;                #小于1000B内容不壓縮

gzip_buffers    16    32k;                #壓縮緩存的個數和容量

gzip_types    text/plain    application/xml;        #指定壓縮檔案類型

gzip_comp_level    2;                    #壓縮級别為2,數字越大壓縮效果越好

client_body_buffer_size    128k;                        #允許用戶端請求緩存大小

client_max_body_size    100m;                             #允許請求的最大檔案容量

large-client_header_buffers    4    8k;                #

proxy_buffering    on;                                           #開啟代理緩沖功能

proxy_buffer_size    8k;                                        #第一部分響應資料的緩存大小

proxy_buffers    8    128k;                                     #響應資料的緩存個數和容量

proxy_cache_path    /usr/local/nginx/cache    levels=1:2    keys_zone=one:100m    inactive=1d    max_size=2G;    

#設定緩存目錄,levels設定緩存個數,keys_zone定義緩存名字和容量,inactive定義緩存存活時間,max_size定義硬碟的緩存容量

proxy_connect_timeout    60s;            #與後端伺服器建立TCP連接配接握手逾時時間

upstream servers {

#ip_hash;        iphash確定相同用戶端ip使用相同的後端伺服器,不适用就預設輪詢

server    192.168.1.3:80    max_fails=3    fail_timeout=30s    weight=2;

server    192.168.1.4:80    max_fails=3    fail_timeout=30s    weight=2;

server    192.168.1.5:80    max_fails=3    fail_timeout=30s    weight=2;

    listen    80;

    server_name    web.test.com;

    access_log    logs/host.access.log    main;

    location / {

proxy_pass http://servers;

proxy_cache one;

proxy_set_header X-Forwarded-For $remote_addr;

    }

}}

配置完成執行

echo "/usr/local/nginx/sbin/nginx" >> /etc/rc.local

浏覽器通路192.168.1.2 或者122.126.152.183 重新整理将分别得到不同的web頁面資訊

三、Nginx rewrite規則總結

nginx的rewrite文法格式和apache非常相似,rewrite regex replacement [flag],其中flag可以被設定為last結束目前指令并重新搜尋location比對、break結束目前rewrite指令、redirect臨時重定向302、permanent永久重定向301。

rewrite位址重寫及return應用的文法解析:

##根據浏覽器辨別,通路資源重定向到指定檔案目錄,下面用IE浏覽器示例

if ($http_user_agent ~ MSIE ) {

rewrite ^(.*)$ /msie/$1 break;

##将移動用戶端的請求重定向到其他伺服器 

if    ($http_user_agent ~* '(iphone|ipod)' )  {

rewrite    ^.+    http://mobile.site.com$uri;

##使用者使用POST方式請求資料時候,傳回405

if ($request_method = POST ) {

return 405;

rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;

rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra last;

##通路admin時候重定向到admin目錄

location /php_admin {

rewrite ^/php_admin/.*$ /admin permanent;

本文轉自super李導51CTO部落格,原文連結:http://blog.51cto.com/superleedo/1896032 ,如需轉載請自行聯系原作者

繼續閱讀