如何使用Gunicorn和Flask正确配置Nginx?

时间:2019-01-02 08:46:55

标签: nginx flask gunicorn nginx-reverse-proxy

我正在http://ip:8000上运行Gunicorn服务器。我在同一台计算机上有nginx服务器,监听http://ip:8080

当我不经过nginx而直接访问http://ip:8000(gunicorn)时,没有任何错误。我的webapp运行正常。

但是当我访问http://ip:8080(nginx)时,它将打开我的应用程序的第一个登录页面。但是一旦我输入了用户名和密码。它解决了CORS错误:

Access to XMLHttpRequest at 'http://ip:8000/login' from origin 'http://ip:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

当我在flask代码中添加以下代码时,它不会引发CORS错误,但是现在出现了一个新问题。输入用户名和密码后,它将允许我登录,然后将我重定向回登录页面,并且地址栏中的URL更改为“ http://ip:8000/login”,这是gunicorn服务器的地址。

from flask_cors import CORS
CORS(app)

我的nginx conf文件看起来像这样:

server{
    listen 8080;
    server_name ip;
    root /path/to/root;
    access_log /path/to/access.log;
    error_log /path/to/error.log;
    location /{
            proxy_pass http://ip:8000;
            add_header 'Access-Control-Allow-Origin' "$http_origin";
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Headers' 'User-Agent,Keep-Alive,Content-Type';
            proxy_set_header Host  $host:$server_port;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_redirect off;
            proxy_set_header X-Forwarded-Proto $scheme;
            }
    }

有人可以帮我解决这个问题吗?

0 个答案:

没有答案