与gunricorn + nginx的Flask重定向(url_for)错误

N. *_* Ma 12 python reverse-proxy nginx flask gunicorn

我的烧瓶应用程序中的重定向(url_for)函数出现问题.

任何重定向(url_for("index"))行将应用程序从domain.com/app重定向到ip-addr/app,其中ip-addr是我自己的客户端机器ip,而不是服务器的.

这让我很困惑,我不知道问题究竟发生在哪里,因为它只发生在服务器而不是任何本地测试.

细节:

我正在使用http://flask.pocoo.org/snippets/35/中的反向代理设置.我的nginx配置是这样设置的

location /app {
                proxy_set_header X-Script-Name /app;
                proxy_set_header Host $http_host;
                proxy_set_header X-Forwarded-Host $proxy_add_x_forwarded_for;
                proxy_redirect off;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Scheme $scheme;
                proxy_connect_timeout 60;
                proxy_read_timeout 60;
                proxy_pass http://localhost:8000/;
        }
Run Code Online (Sandbox Code Playgroud)

我有一个gunicorn运行我的烧瓶应用程序作为一个暴发户的任务.任何提示?

编辑:

所以我挖了一下,发现这个git报告有类似的问题,https://github.com/omab/django-social-auth/issues/157.

Nginx - Gunicorn通过localhost(127.0.0.1:1234)为Nginx服务.不幸的是,当我使用社交平台进行身份验证时,重定向URL social-auth将它们发送到127.0.0.1:1234/twitter/complete,这显然无法通过客户端的浏览器解析.

看来我的Flask应用程序没有得到备忘录来更新其重定向路由.

N. *_* Ma 12

我找到了解决方案.我必须使用redirect(url_for(location, _external=True))我的所有重定向.

似乎url_for(x, _external=True)需要我的nginx proxy_set_header中的所有变量来构造url,而url_for(x)不是这样做.

这适用于服务器和本地开发.


小智 8

添加include proxy_params为我修复了它。

location / {
    proxy_pass http://...;
    include proxy_params;
}
Run Code Online (Sandbox Code Playgroud)

  • +1 这个答案,因为它解决了它发生的问题(nginx 代理)。接受的答案更像是烧瓶中的解决方法。但是,如果您使用 plesk(或其他虚拟化)proxy_params 将不存在于默认位置 `/etc/nginx/proxy_params`。要么设置正确的路径,要么像@Mauricio 的回答一样手动设置 (3认同)

Mau*_*cio 5

有同样的问题。您的解决方案是使应用程序有必要通过在每个环境的配置变量上设置它来了解它正在运行哪个域。我在这里发现解决方案实际上是重写 nginx proxy_pass 上的标头,如下所示:

location /api {
       # Define the location of the proxy server to send the request to
       proxy_pass http://web:8000;

       # Redefine the header fields that NGINX sends to the upstream server
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

       # Define the maximum file size on file uploads
       client_max_body_size 5M;
   }
Run Code Online (Sandbox Code Playgroud)