NGINX proxy_pass 重写资产 uri

NGINX proxy_pass rewrite asset uri

我正在尝试通过 subdomian 做一个基本的 NGINX 反向代理,到 localhost/folder 并且很难让它重写我的资产+链接。

我的 http://localhost:8080/myapp/ 工作得很好,但是通过 NGINX+subdomain 它在子文件夹资产上失败了。

我想我对 NGINX 的 'rewrite' 条款感到困惑。

如何重写 HTML 到客户端浏览器以删除 /myapp/ 上下文?

server {
    listen       443 ssl;
    server_name  app1.domain.com;
    location / {
        rewrite ^/myapp/(.*) / break; # this line seems to do nothing
        proxy_pass http://localhost:8080/myapp/;
    }
}

我期待我的结果 HTML(通过 https://app1.domain.com) to be rewritten without the subfolder /myapp/, so when assets are requested they can be found instead of a 404 against https://app1.domain.com/myapp/assets/. It should just be https://app1.domain.com/assets/(如果我手动去那里他们工作)

--谢谢。

作为 nginx proxy_pass 文档 states:

In some cases, the part of a request URI to be replaced cannot be determined:

...

When the URI is changed inside a proxied location using the rewrite directive, and this same configuration will be used to process a request (break):

location /name/ {
    rewrite    /name/([^/]+) /users?name= break;
    proxy_pass http://127.0.0.1;
}

In this case, the URI specified in the directive is ignored and the full changed request URI is passed to the server.

因此,在将 /myapp/assets/some_asset URI 重写为 /assets/some_asset 并使用 break 标志后,使用此配置块,nginx 将忽略 proxy_pass 上的 /myapp/ 后缀指令并将 /assets/some_asset 请求传递给您的后端。不管多么奇怪,你需要的是改用这个重写规则:

rewrite ^(/myapp/.*)$  break;

另一个(可能更好)解决方案是使用两个 location 块:

location / {
    proxy_pass http://localhost:8080/myapp/;
}
location /myapp/ {
    proxy_pass http://localhost:8080;
}

根据 Ivan 的回复并最终确定我的解决方案为:

server {
    listen       443 ssl;
    server_name  app1.domain.com;
    location / {
        sub_filter '/myapp/'  '/'; # rewrites HTML strings to remove context
        sub_filter_once off; # ensures it loops through the whole HTML (required)
        proxy_pass http://localhost:8080/myapp/;
    }
}