代码之家  ›  专栏  ›  技术社区  ›  Woodsy

带第三方应用程序的nginx反向代理

  •  0
  • Woodsy  · 技术社区  · 7 年前

    我将nginx与几个第三方应用程序一起使用。当第三方应用程序引用具有绝对路径的资源或链接时,我遇到问题。如果我拥有该应用程序,我将能够对路径进行更改,以包括每个应用程序的nginx位置,但由于我无法修改第三方应用程序,我正在查看 nginx.conf 提交答案。

    NGNX.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开发多个应用程序,我相信每个应用程序都需要自己的位置。有什么办法解决这个问题吗?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Woodsy    7 年前

    我可以用 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/";
    }