nginx proxy_pass 反向代理的用法

反向代理简单来说就是代理服务器,如下图:
这里写图片描述

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;
}

都可实现:
这里写图片描述


  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值