具有不同上下文路径的 Nginx 反向代理

ola*_*ert 5 proxy tomcat nginx

我正在尝试使用 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/;
    }

}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Tar*_*ani 5

首先,没有什么比透明地将后端从根域代理到添加了基本 url 的域更合适的了。

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

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

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

如何使用 NGINX 代理对特定 URL 的调用以进行洪水泛滥?

尽你所能,所有的 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/;
}
Run Code Online (Sandbox Code Playgroud)

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

location /app1/ {
    sub_filter_once off;
    sub_filter '<head>' '<head>\n<base href="/app1/">';
    sub_filter 'src="/' 'src="./';
    sub_filter 'href="/' 'href="./';
}
Run Code Online (Sandbox Code Playgroud)