Search code examples
nginxflaskgunicorn

Redirect and url_for in Flask adds domain twice on prod server via Gunicorn and Nginx


I'm having problems redirecting in Flask on a prod server. Note: This does not happen locally, only when running on a prod server with Nginx and Gunicorn. The problem started when https and a domain was added. I'm not sure whether the problem is with flask or my nginx settings.

My problem occurs for all redirects but here is an example: return redirect(url_for('.login')). The expected ouput here is "domain.com/login", but it redirects to "domain.com%2Cdomain.com/login". When I print the `url_for('.login') it shows "/login".

While looking for solutions I found that it could maybe be something with my nginx settings, so here they are:

server {
    server_name domain.com www.domain.com;

    #Fix for socket.io, dont think this is related
    location /socket.io {
            proxy_pass http://127.0.0.1:8088/socket.io;
            proxy_redirect off;
            proxy_buffering off;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
}

    location / {
            include proxy_params;
            proxy_pass http://127.0.0.1:8088;
    }

listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem; # managed by 
Certbot
ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; # managed 
by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot


}
server {
if ($host = www.domain.com) {
    return 301 https://$host$request_uri;
} # managed by Certbot


if ($host = domain.com) {
    return 301 https://$host$request_uri;
} # managed by Certbot


    listen 80;
    server_name domain.com www.domain.com;
return 404; # managed by Certbot
}

Note that I replaced our domain with "domain.com".

If there's any more information I can supply please let me know.

Edit: Solved it. I had to remove the line include proxy_params;in my nginx config file. I dont know why, but it worked. Now behaviour is as expected. I'm trying to mark this post as solved but it says I need to wait a few days.


Solution

  • Okay so I figured it out. I had to remove the line include proxy_params; in my nginx config file. Not sure why but it worked as expected afterwards.