Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proxy a Flask app running on gunicorn to a subpath in nginx

I have a Flask app running with gunicorn on http://127.0.0.1:4000:

gunicorn -b 127.0.0.1:4000 webapp:app

Now I would like to use nginx as a reverse proxy and forward http://myserver.com/webapp to http://127.0.0.1:4000 in a way that every http://myserver.com/webapp/subpath goes to http://127.0.0.1:4000/subpath.

The proxy/redirect works nicely when not using a subpath:

upstream app {
    server 127.0.0.1:4000 fail_timeout=0;
}

server {
    listen 80 default;
    client_max_body_size 4G;
    server_name _;

    location / {
       proxy_pass http://app;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header Host $http_host;       
    }
}

How can I set

location /webapp {
    #go to my gunicorn app, translate URLs nicely
}

This tip from the Flask developers didn't work: http://flask.pocoo.org/snippets/35/

SOLVED: The snippet http://flask.pocoo.org/snippets/35/ works! I had a few absolute URLs in my templates (e.g. /task/delete) and had to change everything to url_for().

Stupid ... but now it works like expected, I have my app on 'http://myserver.com/subpath'

like image 758
Martin Preusse Avatar asked Jul 22 '13 17:07

Martin Preusse


People also ask

How do Gunicorn and nginx work together?

Nginx and Gunicorn work togetherGunicorn translates requests which it gets from Nginx into a format which your web application can handle, and makes sure that your code is executed when needed. They make a great team! Each can do something, which the other can't.

Is Gunicorn a proxy?

gunicorn-proxy is a Docker turnkey reverse proxy for gunicorn. To use it you only need to set one piece of configuration—The hostname and port of your gunicorn server.


1 Answers

I solved my problem: The snippet http://flask.pocoo.org/snippets/35/ does work, I was so stupid to have absolute URLs in my templates. I changed that to url_for() and now it works like charm.

like image 94
Martin Preusse Avatar answered Oct 09 '22 07:10

Martin Preusse