转自: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; } }