gpt4 book ai didi

nginx - 在nginx反向代理后面处理flask url_for

转载 作者:行者123 更新时间:2023-12-04 11:23:58 37 4
gpt4 key购买 nike

我有一个使用 nginx 进行反向代理/ssl 终止的 flask 应用程序,但是在 flask 中使用 url_for 和重定向时遇到了麻烦。

nginx.conf 条目:

location /flaskapp {
proxy_pass http://myapp:8080/;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

这个想法是用户导航到
https://localhost:port/flaskapp/some/location/here
这应该传递给 flask
http://localhost:8080/some/location/here
这在导航到定义的路线时相当有效,但是如果路线有 redirect(url_for('another_page')) ,浏览器被定向到
http://localhost:8080/another_page
并且失败了,当我真正想去的 URL 是:
https://localhost:port/flaskapp/another_page
我已经针对类似情况尝试了其他几个答案,但似乎没有一个完全符合我在这里所做的。我试过使用 _external=True , 设置 app.config['APPLICATION_ROOT'] = '/flaskapp'和许多不同的迭代 proxy_set_header nginx.conf 中的命令没有运气。

更复杂的是,我的 flask 应用程序正在使用 flask-login和 CSRF cookie。当我尝试设置 APPLICATION_ROOT 时应用程序停止考虑由 flask-login 设置的 CSRF cookie有效,我认为这与起源有关。

所以我的问题是,我如何做到这一点,以便在 flask 返回 redirect() 时到客户端,nginx 知道它给定的 URL 需要 flaskapp写进去了吗?

最佳答案

我设法通过一些更改修复了它。

更改 1. 将/flaskapp 添加到我的 Flask 应用程序中的路由。这消除了对 URL 重写的需要并大大简化了事情。

更改 2. nginx.conf 更改。我在 location 块中添加了 logc 以将 http 请求重定向为 https,新配置:

location /flaskapp {
proxy_pass http://myapp:8080/;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# New configs below
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
# Makes flask redirects use https, not http.
proxy_redirect http://$http_host/ https://$http_host/;
}

虽然我没有“解决”引入基于已知前缀的条件重写的问题,但由于我只需要一个前缀用于这个应用程序,因此将它烘焙到路由中是一个可接受的解决方案。

关于nginx - 在nginx反向代理后面处理flask url_for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58633027/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com