用DirectorySlash指令的Nginx反向代理到Apac

用DirectorySlash指令的Nginx反向代理到Apac

本文介绍了使用DirectorySlash指令的Nginx反向代理到Apache的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要反向代理到在本地主机上运行的 Apache 服务器.问题在于,作为其 DirectoryRewrite 指令的一部分,Apache将请求重定向到不带尾部正斜杠的目录,而重定向到具有尾部正斜杠的目录.当您转到 https://myhost/sw/myapp/时,以下nginx设置可以正常工作,但是如果您忘记尾随的斜杠,最终您将被重定向到 http://myhost:8080/sw/myapp .缺少禁用 Apache DirectoryRewrite 指令的方法,如何确保将/始终添加到任何请求的末尾,以使Apache不会重定向?

I need to reverse proxy to an Apache server running on the localhost. The problem is that Apache redirects requests to directories without a trailing forward slash, to the directory with a trailing forward slash, as part of its DirectoryRewrite directive. The below nginx setup works fine when you go to https://myhost/sw/myapp/ but if you forget the trailing forward slash you end up being redirected to http://myhost:8080/sw/myapp. Short of disabling the Apache DirectoryRewrite directive what can I do to make sure that the / is always added to the end of any request so that Apache does not redirect?

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;
    }

推荐答案

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

If the upstream server is redirecting to http://example.com:8080/ (rather than http://127.0.0.1:8080/) you will need to change or add another proxy_redirect statement. See this document for details.

例如:

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

或者如您在评论中所述:

Or as you stated in comments:

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

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

The proxy_redirect values need to exactly match the beginning of the Location: header in the 3xx response. You can use curl -I to identify the exact contents of that response header.

这篇关于使用DirectorySlash指令的Nginx反向代理到Apache的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 00:10