【问题标题】:Nginx reverse proxy to Apache with DirectorySlash directive使用 DirectorySlash 指令的 Nginx 反向代理到 Apache
【发布时间】:2019-01-24 18:48:13
【问题描述】:

我需要反向代理到在本地主机上运行的Apache 服务器。问题是 Apache 将请求重定向到没有尾部正斜杠的目录,重定向到带有尾部正斜杠的目录,作为其 DirectoryRewrite 指令的一部分。当您转到 https://myhost/sw/myapp/ 时,下面的 nginx 设置工作正常,但如果您忘记了尾部的正斜杠,您最终会被重定向到 http://myhost:8080/sw/myapp。如果没有禁用 Apache DirectoryRewrite 指令,我该怎么做才能确保始终将 / 添加到任何请求的末尾,以便 Apache 不会重定向?

server {
    client_max_body_size 10240M;
    listen      443 ssl;
    server_name  "";

    ssl_certificate      ../ssl/server.crt;
    ssl_certificate_key  ../ssl/server.key;

    ssl_session_timeout  5m;

    ssl_protocols  SSLv2 SSLv3 TLSv1;
    ssl_ciphers  HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers   on;

    location /sw {
        proxy_pass  http://127.0.0.1:8080/sw;
        proxy_redirect ~^http://127.0.0.1:8080/sw/([^.]*[^/])$ https://$host/sw/$1/;
        proxy_redirect http://127.0.0.1:8080/ https://$host/;
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        proxy_buffering off;
        proxy_set_header        HOST            $host;
        proxy_set_header        Referer         $http_referer;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        error_page 301 302 303 = @handle_redirect;
    }

【问题讨论】:

  • 如果 Apache 重定向到 http://myhost:8080/,您可能需要一个 proxy_redirect http://myhost:8080/ https://myhost/;。如果您使用 curl -I,您可以在 3xx 响应中看到 Location: 标头的确切文本。
  • 我确实做到了,而且效果很好。最后我用$host替换了myhost,以防myhost发生变化。请将您的回复作为答案发布,以便我给予您信任。

标签: apache nginx


【解决方案1】:

如果上游服务器重定向到http://example.com:8080/(而不是http://127.0.0.1:8080/),您将需要更改或添加另一个proxy_redirect 语句。详情请见this document。

例如:

proxy_redirect http://example.com:8080/ https://example.com/;

或者如你在 cmets 中所说:

proxy_redirect http://$host:8080/ https://$host/;

proxy_redirect 值需要与 3xx 响应中 Location: 标头的开头完全匹配。您可以使用curl -I 来识别该响应标头的确切内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-06
    • 2020-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 2018-05-10
    • 2017-08-09
    • 2018-02-02
    相关资源
    最近更新 更多