nginx配置反向代理與負載均衡

nginx服務器功能強大,可以用於反向代理也可以用於負載均衡。

一、反向代理配置

location / {
    proxy_pass http://sunpy.com;
 }

其中proxy_pass表示當前server配置的代理映射。

效果如下圖所示:

配置反向代理的常用指令

proxy_redirect off;
重寫後端服務器的location和refresh頭。
proxy_set_header Host $host;
重寫發送給後端服務器的請求頭內容。
proxy_connect_timeout 300;
代理服務器接收請求到連接後端服務器的最長等待時間。
proxy_buffer_size 4k;
後端響應的緩衝區數量和大小。
proxy_buffers 4 32k;
請求後端的緩衝區數量和大小。
proxy_busy_buffers_size 64k;
當代理服務器忙時,緩衝區的最大值。
proxy_send_timeout 300
將超時與請求傳輸到代理服務器分配。
proxy_read_timeout 300
NGINX等待獲取請求響應的時間。

二、負載均衡配置

負載均衡的策略

1、輪詢機制(默認)
就是按照時間順序將請求發送到不同的server。例:使用默認的輪詢,nginx將請求分發到不同的server。

upstream sunpy.com {
        server  192.168.4.149:8088;
        server  192.168.27.13:8088;
}

2、通過ip生成hash值均勻分配到服務器 ip_hash

upstream sunpy.com {
        ip_hash;
        server  192.168.4.149:8088;
        server  192.168.27.13:8088;
}

3、使用最少連接數 least_conn

upstream sunpy.com {
        least_conn;
        server  192.168.4.149:8088;
        server  192.168.27.13:8088;
}

配置example:

upstream myserver {
	server 192.168.3.4;
	server 192.168.3.5;
}
server {
        listen       80;
        server_name  localhost;

        location / {
			proxy_pass http://myserver;
            #root   html;
            #index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
}

參考文章:

http://www.nginx.cn/doc/standard/httpproxy.html

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