【问题标题】:Nginx reverse proxy with different context path具有不同上下文路径的 Nginx 反向代理
【发布时间】:2018-03-18 13:13:04
【问题描述】:

我正在尝试使用nginx反向代理同一主机/端口上的多个Web应用程序,使用不同的路径来区分应用程序。

我的 nginx 配置如下所示:

proxy_set_header Host $http_host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $proxy_connection;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $proxy_x_forwarded_proto;
proxy_set_header X-Forwarded-Ssl $proxy_x_forwarded_ssl;
proxy_set_header X-Forwarded-Port $proxy_x_forwarded_port;

upstream app1 {
    server 192.168.0.1:8080;
}
upstream app2 {
    server 192.168.0.2:8080;
}

server {
    server_name my-application-server;
    listen 80;

    location /app1/ {
        proxy_pass http://app1/;
    }
    location /app2/ {
        proxy_pass http://app2/;
    }

}

这会正确代理对我的应用上各个页面的任何请求 - 例如http://my-application-server/app1/context/login,但我的应用程序中的任何超链接都已损坏,因为它们缺少路径的 app1 部分 - 例如他们将我引导至http://my-application-server/context/login-success 而不是http://my-application-server/app1/context/login-success

我尝试为proxy_redirectrewrite 添加各种值,但我所做的一切都无法说服这些链接正确呈现。

我的应用程序是在 tomcat 中运行的 java webapp,如果这有什么不同的话。我见过其他解决方案,我可以更改我的 webapp 的上下文路径,但我需要 nginx 透明地代理请求,而无需配置 tomcat 以了解 nginx 路径。

【问题讨论】:

    标签: tomcat nginx proxy


    【解决方案1】:

    首先,没有什么能像透明地将后端从根域代理到添加了基本 URL 的域一样。

    如果您想将 http://xyz/abc 代理到 http://def,则无法 100% 保证一切正常。您需要特定于应用程序的更改

    如果您的后端 API 不返回访问当前 url 的 url,那么您无需担心 proxy_pass。但是,如果您有一个 html,那么您需要修复所有遇到的问题。

    查看我为 deluge 后端创建的简单配置

    How to proxy calls to specific URL to deluge using NGINX?

    正如您所见,所有 sub_filter 都已完成以修复 CSS、JavaScript 和 HTML 中的 url。我必须运行它,发现问题,然后实施修复。以下是供您参考的配置

    location ~* /deluge/(.*) {
        sub_filter_once off;
        sub_filter_types text/css;
        sub_filter '"base": "/"' '"base": "/deluge/"';
        sub_filter '<head>' '<head>\n<base href="/deluge/">';
        sub_filter 'src="/' 'src="./';
        sub_filter 'href="/' 'href="./';
        sub_filter 'url("/' 'url("./';
        sub_filter 'url(\'/' 'url(\'./';
    
        set $deluge_host 192.168.33.100;
        set $deluge_port 32770;
        proxy_pass http://$deluge_host:$deluge_port/$1;
        proxy_cookie_domain $deluge_host $host;
        proxy_cookie_path / /deluge/;
        proxy_redirect  http://$deluge_host:$deluge_port/ /deluge/;
    }
    

    您可以根据您的应用自定义上述内容。但以下是您需要的

    location /app1/ {
        sub_filter_once off;
        sub_filter '<head>' '<head>\n<base href="/app1/">';
        sub_filter 'src="/' 'src="./';
        sub_filter 'href="/' 'href="./';
    }
    

    【讨论】:

    • 感谢您的回答 - 很遗憾没有简单的解决方案,但您的回答足以让我开始弄清楚我的应用程序的规则。
    猜你喜欢
    • 1970-01-01
    • 2016-09-14
    • 1970-01-01
    • 2018-03-24
    • 2019-08-05
    • 2019-07-28
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    相关资源
    最近更新 更多