Nginx转发代理配置
作者:zhanhailiang 日期:2013-01-29
需求:
由于系统集成需求,需要将www.hwtrip.com集成到itravel.smartcom.cc中。
想法:
浏览器访问itravel.smartcom.cc/trip/****,通过Nginx将请求转发到www.hwtrip.com/$1?$query_string&from=itravel。
做法:
添加Nginx配置:匹配location中/trip/关键字,将该请求转发到www.hwtrip.com/$1?from=itravel
# 注意这里是匹配请求URI的路径是否含关键字/trip/,所以必须加上~, 若不加~,则相当于查找根目录下是否含有trip目录,详见【location】location ~ /trip/ { proxy_pass http://www.hwtrip.com:80; proxy_redirect default; proxy_set_header Host www.hwtrip.com; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 转发前的请求参数会默认添加到新参数后面 ,详见【rewrite】 rewrite ^/trip/(.*)$ /$1?from=itravel break; break;}
最后测试用例如下:
==> 请求头 <==GET /trip/t.html HTTP/1.1Host: itravel.smartcom.ccConnection: keep-aliveCache-Control: max-age=0Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.56 Safari/537.17Accept-Encoding: gzip,deflate,sdchAccept-Language: en-US,en;q=0.8Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3Cookie: ******==> 响应头 <==HTTP/1.1 200 OKServer: nginxDate: Tue, 29 Jan 2013 07:38:11 GMTContent-Type: text/html; charset=utf-8Transfer-Encoding: chunkedConnection: closeContent-Encoding: gzip