【问题标题】:Redirect IP to host name in NGINX将IP重定向到NGINX中的主机名
【发布时间】:2013-07-28 23:44:32
【问题描述】:

我想使用重写指令将我网站的每个 IP 地址重定向到该网站的主机名,而不是像这样在 NGINX 中使用 proxy_pass 指令访问该网站

 proxy_pass http://host/name ;

使用 NGINX 作为代理适用,但我无法更改我的脚本来重写地址并同时代理我的请求。我尝试使用 Rewrite 指令,但找不到正确的语法。

【问题讨论】:

    标签: redirect url-rewriting nginx proxy ip


    【解决方案1】:

    使用重写指令更改主机将导致重定向。这意味着客户端需要向新主机发布另一个请求,然后,您可以 proxy_pass 这个请求。在这种情况下,客户端(例如浏览器)中的 URL 会发生变化,例如 'http://*.*.*.*:port/uri?request_string' -> 'http://host/uri?request_string'。

    通常,我们使用 rewrite 指令来更改将被 proxy_passed 的请求的 URI。如果要更改主机,请使用proxy_set_header。一个例子:

    location ~* "^/maishenme/(knowse|knowdetail|iget|ilist|initem|i?compare)(.*)?$" {
            rewrite "^/maishenme/(.*)?$" /$1 break;
            proxy_pass http://***.xxx.com;
            proxy_set_header Host "internal.xxx.com";
            break;
    }
    

    并且在这种情况下,从客户端来看,url 没有改变,但是对于后端服务器,您可以打印主机字段并看到它已更改为“internal.xxx.com”

    【讨论】:

    • 您能否为我解释一下这段代码以及如何使用网站的真实 IP 和主机名对其进行测试
    • 如果可以接受 301 或 302 重定向,使用“redirect”指令,然后使用 proxy_pass。如果要更改 proxy_pass 中的主机字段,可以使用 proxy_set_header 替换它。阅读手册并尝试更多。
    猜你喜欢
    • 2011-03-26
    • 2012-07-23
    • 2019-01-28
    • 2017-02-20
    • 2016-04-12
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多