【问题标题】:Reverse proxy nginx to itself将 nginx 反向代理到自身
【发布时间】:2020-12-14 19:37:22
【问题描述】:

我目前正在托管一个托管在 URL 根目录中的单页响应应用程序,如下所示:

server {
    listen       80;
    server_name  localhost;
    
    location / {
        root   /var/www/html;
        try_files $uri /index.html;
    }
}

我需要将站点放在 AWS 弹性负载均衡器后面,同时更改路径,以便所有内容都在 /support 目录中,例如http://example.com/index.html -> http://example.com/support/index.html.

AWS ALB 不支持 URL 重写,因此我必须在服务器上的 nginx 配置中执行此操作。首先,我尝试将配置更改为:

server {
    listen       80;
    server_name  localhost;
    
    location /support {
        alias   /var/www/html;
        try_files $uri /index.html;
    }
}

这种方法有效,但 javascript 内容中的 URL 不包含 /support 路径(例如,它们包含 http://example.com/script.js 而不是 http://example.com/support/script.js)。

然后我尝试创建一个反向代理配置以将 /support 代理到 /,这很遗憾地将 nginx 置于无限循环中,直到它耗尽工作线程:

server {
    listen       80;
    server_name  localhost;
    
    location /support {
        proxy_pass http://localhost:80;
    }
    
    location / {
        root   /var/www/html;
        try_files $uri /index.html;
    }

}

我很困惑为什么请求会进入反向代理循环? proxy_pass 不应该在代理请求之前删除/support 前缀,因此它不应该被/support 位置再次“捕获”吗?

【问题讨论】:

  • proxy_pass 不会重写任何内容。如果可以,接收请求的任何服务器如何知道URI 正确响应?

标签: nginx


【解决方案1】:

只是猜测。

您想在/ 上提供一些东西吗?

如果没有 - 这很容易:

server
{
    listen       80;
    server_name  localhost;
    
    location /support/
    {
        alias /var/www/html/;
        try_files $uri $uri/ /index.html;
    }
    
    location /
    {
        return 303 http://localhost/support$request_uri;
    }
}

如果它不起作用(使用它们 - 或不使用 - 通常会有所不同),请使用结尾的斜线。

使用alias 代替root,这样/support 就不会添加到/var/www/html 文件夹中。

一切都被重定向到/support


如果你想在/ 上提供与/support 不同的东西:

/support 中使用sub_filtersubs_filter 即时重写您的源代码链接,这样他们就永远不会使用/

如果您的源代码(或 proxy_pass 后端)中有重定向 - 您需要 proxy_redirect 和/或 Lua 来即时捕获和更改它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 2019-03-14
    • 2016-03-12
    相关资源
    最近更新 更多