轉自:http://chazor.org/html/74.html
在官方提供的LoadBalanceExample基礎上,修改
http {
upstream myproject {
server 127.0.0.1:8000 weight=3;
server 127.0.0.1:8001;
server 127.0.0.1:8002;
server 127.0.0.1:8003;
}
server {
listen 80;
server_name www.domain.com;
location / {
proxy_pass http://myproject;
}
}
}
加幾行
http {
upstream myproject {
server 127.0.0.1:8000 weight=3;
server 127.0.0.1:8001;
server 127.0.0.1:8002;
server 127.0.0.1:8003;
}
server {
listen 80;
server_name www.domain.com;
location / {
proxy_store off;
proxy_redirect off;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://myproject;
}
}
}
在Nginx中的默認Proxy是只能對后面Real Server做端口轉發的,而不能做域名轉發。如果想使用Nginx對后端是同一IP、同一端口 轉發不同的域名則需要配置Nginx Proxy。
這個是因為默認情況下:
proxy_set_header Host $proxy_host;
這樣就等於前端輸入域名后到nginx這里直接轉換成IP進行轉發了。
於是我們需要修改proxy_set_header的參數。
proxy_set_header Host $http_host;
下面這個例子中backend1權重為5,其他默認為1,最大失效次數3次,如果30秒內沒有響應就認為是失效了。
upstream lb {
server cache.opencfg.com weight=5;
server app.opencfg.com max_fails=3 fail_timeout=30s;
}
server {
listen 80;
server_name www.opencfg.com;
location / {
proxy_store off;
proxy_redirect off;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_pass http://lb;
}
}