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

mst*_*son 5 nginx flask flask-login

我有一个使用 nginx 进行反向代理/ssl 终止的烧瓶应用程序,但是在烧瓶中使用 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;
}
Run Code Online (Sandbox Code Playgroud)

这个想法是用户导航到

https://localhost:port/flaskapp/some/location/here

这应该传递给烧瓶

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-loginCSRF cookie。当我尝试设置APPLICATION_ROOT应用程序时,停止考虑由flask-login有效设置的 CSRF cookie ,我认为这与来源有关。

所以我的问题是,我如何做到这一点,以便当 Flask 将 a 返回redirect()给客户端时,nginx 知道它给定的 URL 需要flaskapp写入其中?

mst*_*son 5

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

更改 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/;
}
Run Code Online (Sandbox Code Playgroud)

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