首页 > 解决方案 > 使用 DirectorySlash 指令的 Nginx 反向代理到 Apache

问题描述

我需要反向代理到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;
    }

标签: apachenginx

解决方案


如果上游服务器重定向到http://example.com:8080/(而不是http://127.0.0.1:8080/),您将需要更改或添加另一个proxy_redirect语句。有关详细信息,请参阅此文档

例如:

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

或者正如您在评论中所说:

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

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


推荐阅读