【问题标题】:Nginx rewrite sends traffic to IP address, not URLNginx 重写将流量发送到 IP 地址,而不是 URL
【发布时间】:2021-01-23 17:00:01
【问题描述】:

我已将 nginx 设置为 docker 微服务的反向代理。有一个位置块将 url 从/wrong 重写为/right

    server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;
        server_name example.com;

        location /right {
            proxy_pass http://microservice_servers;
        }

        location /wrong {
            rewrite ^/wrong/(\w+) /right/$1 redirect;
        }
    }

这样做的目的是将url从https://example.com/wrong/otherstuff重写为https://example.com/right/otherstuff。 但实际发生的是,它重写为http://<ip_address>/right/otherstuff

(一个可能的复杂因素是我无法控制此站点的证书。这些由客户端控制,客户端将它们放在我们服务器前面的应用程序网关上。所以我的 nginx 配置只处理 http端口 80 的流量,没有来自 443 的 https。我不确定这是否真的相关,但以防万一。)

我尝试了对重写块的各种更改,包括添加$server_name,将标志更改为last(返回正确的内容但不更改url),以及将标志更改为@987654330 @(不返回预期的内容)。

知道这里发生了什么吗?

【问题讨论】:

  • 标题写着“重写”,但规则是重定向?
  • 它使用带有redirect标志的rewrite指令:nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite
  • 那么,按照文档,接收到的 URL 被更改,放入 302,并发送回客户端(这是处理 HTTPS 的应用程序网关)?并且大概是应用程序网关处理 302,并将新 URL 发送回 NGINX?因为这就是你最终进入/right 的方式。 rewrite 本身不会导致 NGINX 在内部在 /right 处重新启动。您可能想要对交换的消息进行wireshark。

标签: nginx nginx-reverse-proxy


【解决方案1】:

默认情况下,您的rewrite...redirect 语句将生成一个 302 响应,其中包含在 HTTP 位置响应标头中指定的完整 URL。

您可以使用curl -I https://example.com/wrong/otherstuff 确认这一点。

Nginx 根据原始请求填写协议和域名。这个server 块通过http 接收请求,我们可以从您的问题中推断出 Host 标头使用其 IP 地址。

您需要在 rewrite 语句中指定完整的 URL:

rewrite ^/wrong/(\w+) https://example.com/right/$1 redirect;

或者,使用相对 URL:

absolute_redirect off;

详情请见this document

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 2020-08-16
    • 2013-02-27
    • 2012-04-29
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多