nginx proxy_pass 通配符配置

nginx proxy_pass 通配符配置

我有一个像这样的 apache 配置:

<VirtualHost *:80>
    ProxyPass /app http://localhost:8080/app
    ProxyPassReverse /app http://localhost:8080/app
    ProxyPass /images http://localhost:8080/app/images
    ProxyPassReverse /images http://localhost:8080/app/images
</VirtualHost>

我正在尝试将其转换为 nginx 配置。到目前为止,我已经

server {
    listen       80;
    server_name  localhost;

    location /app {
        proxy_set_header X-Forwarded-Host $host:$server_port;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://localhost:8080/app;
    }

    location /app/images {
        proxy_set_header X-Forwarded-Host $host:$server_port;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://localhost:8080/app/images;
    }
    ...
}

这有很多重复。请帮我弄清楚如何只用一个位置来处理所有子路径。此外,我不想启用任何(通配符)子路径,而是启用一组已知子路径。比如说,我想启用localhost/applocalhost/app/images,而不启用其他。就像上面一样,但更短。这可能吗?

答案1

nginx 允许使用正则表达式来匹配位置,假设您可能需要index.html。否则只需将其删除。

server {
    listen       80;
    server_name  localhost;

    location ~ ^/app/(index.html|images)? {
        proxy_set_header X-Forwarded-Host $host:$server_port;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://localhost:8080;
    }
    ...
}

答案2

您可以简单地使用location这样的块:

location /app {
    proxy_set_header X-Forwarded-Host $host:$server_port;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://localhost:8080;
}

proxy_pass不包含路径部分时,nginx 会将请求的规范化 URI 附加到proxy_pass指令的主机部分。

相关内容