如何在Nginx中使用proxy_redirect

发布时间:2021-03-25 17:23:03 作者:Leah
来源:亿速云 阅读:392

如何在Nginx中使用proxy_redirect?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

server {
 listen 80;
 server_name www.boke.com;
 location / {
  proxy_pass http://192.168.1.154:8080;
  proxy_redirect off;
 }
 }

此时我们通过curl查看结果得出

[root@localhost nginx]# curl -I http://www.boke.com/wuman
HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Thu, 24 Dec 2015 12:02:00 GMT
Content-Type: text/html; charset=iso-8859-1
Connection: keep-alive
Location: http://192.168.1.154:8080/wuman/

这里location为带有后端服务器实际地址跟端口的响应头信息这样在实际线上是不允许的所以这里我们打算通过proxy_redirect将被代理服务器的响应头中的location字段进行修改后返回给客户端

server {
 listen 80;
 server_name www.boke.com;
 location / {
  proxy_pass http://192.168.1.154:8080;
  proxy_redirect http://192.168.1.154:8080/wuman/ http://www.boke.com/wuman/;
 }

server {
 listen 80;
 server_name www.boke.com;
 location / {
  proxy_pass http://192.168.1.154:8080;
  proxy_redirect ~^http://192.168.1.154:8080(.*) http://www.boke.com$1;
 }

则curl查看返回结果

[root@localhost nginx]# curl -I http://www.boke.com/wuman
HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Thu, 24 Dec 2015 12:08:34 GMT
Content-Type: text/html; charset=iso-8859-1
Connection: keep-alive
Location: http://www.boke.com/wuman/

此时查看location已经变成了我们想要的结果了。 此时通过replacement 301重定向到了我们新的页面

出处:

proxy_redirect

语法:proxy_redirect [ default|off|redirect replacement ] 

默认值:proxy_redirect default 

使用字段:http, server, location 

如果需要修改从被代理服务器传来的应答头中的"Location"和"Refresh"字段,可以用这个指令设置。

假设被代理服务器返回Location字段为: http://localhost:8000/two/some/uri/

这个指令: 

proxy_redirect http://localhost:8000/two/ http://frontend/one/;

将Location字段重写为http://frontend/one/some/uri/。

在代替的字段中可以不写服务器名:

proxy_redirect http://localhost:8000/two/ /;

这样就使用服务器的基本名称和端口,即使它来自非80端口。

如果使用“default”参数,将根据location和proxy_pass参数的设置来决定。

例如下列两个配置等效:

location / one / {
 proxy_pass http: //upstream:port/two/; 
 proxy_redirect default;
}
location / one / {
 proxy_pass http: //upstream:port/two/; 
 proxy_redirect http: //upstream:port/two/ /one/;
}

在指令中可以使用一些变量:

proxy_redirect http://localhost:8000/ http://$host:$server_port/;

这个指令有时可以重复:

proxy_redirect default;
proxy_redirect http://localhost:8000//; proxy_redirect ; /;

参数off将在这个字段中禁止所有的proxy_redirect指令:

proxy_redirect off;
proxy_redirect default;
proxy_redirect http://localhost:8000/ /; proxy_redirect ; /;

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. 如如何使用journalctl命令?
  2. 如何在nginx中使用http模块

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

nginx proxy redirect

上一篇:怎么在C#中利用Aspose.Cells导出excel

下一篇:怎么在Python中使用Selenium实现异步加载数据

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》