user2672537
user2672537

Reputation: 353

Flask url_for ignoring port

I have a Flask app running on port 5000. My server admin has configured nginx to forward this to port 5001 (sorry if I have the wrong terminology: the Flask app is running on port 5000, but the app is publicly accessible at http://the_url:5001).

All routes accessed directly in the browser work, but any redirect using url_for() seem to result in the port being missed from the URL — i.e. redirect(url_for('index')) redirects to http://the_url/ rather than http://the_url:5001/ (where the @app.route("/") triggers the function index()).

How do I make sure Flask adds the correct port when redirecting? If I change the default port to 5001, the nginx configuration will not work as it expects the app to be runnning on port 5000?

Upvotes: 9

Views: 6079

Answers (2)

jiayi Peng
jiayi Peng

Reputation: 335

add this to your Nginx config: proxy_set_header Host $http_host; or proxy_set_header Host $host:5001

read here

Upvotes: 19

m1yag1
m1yag1

Reputation: 829

Try adding something like this to the nginx config.

location / {
            proxy_pass http://localhost:5000;

            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

            proxy_set_header X-NginX-Proxy true;
        }

This way you can have your flask app running on localhost:5000. If you set up your server { listen 80; } config correctly (at the top of the config) the user should be able to hit port 80 and it will redirect to internal 5000 port. All my url_for() work perfectly.

Upvotes: 0

Related Questions