9

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?

user2672537
  • 343
  • 1
  • 4
  • 11
  • Possible duplicate of [Where do I define the domain to be used by url\_for() in Flask?](http://stackoverflow.com/questions/12162634/where-do-i-define-the-domain-to-be-used-by-url-for-in-flask) – ahmed Oct 14 '15 at 11:19
  • Read commentaries for answer in http://stackoverflow.com/questions/12162634/where-do-i-define-the-domain-to-be-used-by-url-for-in-flask. You should remove 'http' part from config. – Jimilian Oct 14 '15 at 11:42
  • I'd seen previous answers, but setting the `app.config["SERVER_NAME"]` variable stops the site running ... unless I am doing this wrong? (I just set it to: `the_url:5001`) – user2672537 Oct 14 '15 at 12:35
  • @user2672537, you need to setup `SERVER_NAME` = `localhost:5001` – Jimilian Oct 14 '15 at 17:42
  • What helped me was this url (it's old, but still worked): https://flask.palletsprojects.com/en/1.0.x/deploying/wsgi-standalone/#proxy-setups – colidyre Jun 02 '20 at 15:13

2 Answers2

19

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

read here

Community
  • 1
  • 1
jiayi Peng
  • 325
  • 3
  • 11
0

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.

m1yag1
  • 819
  • 7
  • 11