首页 > 解决方案 > 带有 3rd 方应用程序的 NGINX 反向代理

问题描述

我将 NGINX 与几个 3rd 方应用程序一起使用。当第 3 方应用程序使用绝对路径引用资源或链接时,我遇到了问题。如果我拥有该应用程序,我将能够更改路径以包含每个应用程序的 nginx 位置,但由于我无法修改第 3 方应用程序,我正在查看nginx.conf文件以获取答案。

nginx.conf

location /app1/ {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://localhost:8001;
}
location /app2/ {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://localhost:8002;
}

现在在 App1 和 App2 他们引用这样的资源:

<img src='/images/app1_image.xyz'>

这会导致浏览器在以下位置查找文件

http://domainname.com/images/app1_image.xyz

而不是

http://domainname.com/app1/images/app1_image.xyz

如果我有一个应用程序,我可以将位置设置为,/但由于我将 nginx 用于多个应用程序,我相信每个应用程序都需要自己的位置。有没有办法解决这个问题?

标签: nginx

解决方案


我能够通过使用sub_filter此修复每个应用程序的 html 页面中的所有引用来解决此问题。

location /app1/ {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://localhost:8001;

    sub_filter_once off;   
    sub_filter 'href="/' 'href="/app1/';
    sub_filter "href='/" "href='/app1/";
    sub_filter 'src="/' 'src="/app1/';
    sub_filter "src='/" "src='/app1/";
}

location /app2/ {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_pass http://localhost:8002;

    sub_filter_once off;   
    sub_filter 'href="/' 'href="/app2/';
    sub_filter "href='/" "href='/app2/";
    sub_filter 'src="/' 'src="/app2/';
    sub_filter "src='/" "src='/app2/";
}

推荐阅读