Flask url_for忽略端口

use*_*537 7 python flask

我有一个在端口5000上运行的Flask应用程序.我的服务器管理员已配置nginx将其转发到端口5001(对不起,如果我有错误的术语:Flask应用程序在端口5000上运行,但应用程序可公开访问http://the_url:5001).

在浏览器中直接访问的所有路由都可以正常工作,但是使用任何重定向url_for()似乎都会导致URL丢失端口 - 即redirect(url_for('index'))重定向到http://the_url/而不是http://the_url:5001/(@app.route("/")触发函数的地方index()).

如何确保Flask在重定向时添加正确的端口?如果我将默认端口更改为5001,nginx配置将无法正常工作,因为它期望应用程序在端口5000上运行?

jia*_*eng 12

将此添加到您的Nginx配置: proxy_set_header Host $http_host; 或 proxy_set_header Host $host:5001

在这里阅读


m1y*_*ag1 0

尝试将类似的内容添加到 nginx 配置中。

location / {
            proxy_pass http://localhost:5000;

            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

            proxy_set_header X-NginX-Proxy true;
        }
Run Code Online (Sandbox Code Playgroud)

这样你就可以让你的 Flask 应用程序在 localhost:5000 上运行。如果您正确设置server { listen 80; }配置(在配置顶部),用户应该能够访问端口 80,并且它将重定向到内部 5000 端口。我所有的url_for()工作都很完美。