反向代理简单来说就是代理服务器,如下图:
nginx 对反向代理的支持应该是所有http服务器中最容易的。
其配置方法如下:
location /music/{
proxy_pass http://music.baidu.com/;
}
我的测试机是192.168.8.6,因此我在浏览上输入:
192.168.8.6/music/:
可以看到浏览器上的地址并没有变化,这与rewrite显著不同。
我们来看看proxy_pass的说明:
Sets the protocol and address of a proxied server and an optional URI to which
a location should be mapped. As a protocol, “http” or “https” can be
specified. The address can be specified as a domain name or IP address, and
an optional port:
proxy_pass 可以做的几件事是这样的:
- 本地不处理,交给后面处理
这样后面就可以用php, fastcgi, tomcat等处理- 可以切换协议,比如从http切换至https
- 实际上在linux上还可以将底层切换至unix domain socket
再举一些例子:
我之前写过一篇文章:
http://blog.csdn.net/xiaofei_hah0000/article/details/52228779
讲的是nginx如何使用rewrite
现在我想从192.168.8.6/rewrite直接跳转至该文章,反向代理可以这样写:
location /rewrite{
proxy_pass http://blog.csdn.net/xiaofei_hah0000/article/details/52228779;
}
效果:
实现了跳转,是不是很方便。
第二个例子:
京东有很多个活动卖场,比如小米,OPPO,
相应的网址:
http://sale.jd.com/act/K8i1dm7kDZq.html
http://sale.jd.com/act/LdUyPxfzZVb15IrG.html
都是在http://sale.jd.com/act/这个活动栏下的,
如果我们要做代理,应该怎么做呢:
location /act/{
proxy_pass http://sale.jd.com/act;
}
结果跳转到错误页面。
http://sale.jd.com/act/act/LdUyPxfzZVb15IrG.html
有两种方法修改:
location /act/{
proxy_pass http://sale.jd.com/act/;
}
或者:
location /act{
proxy_pass http://sale.jd.com/act;
}
都可实现: