Running Flask app at a url that is not domain root

I am moving a Flask application from apache2 and mod_wsgi environment to Nginx and I am having problems with the urls working correctly.

I want the root page of my application to be displayed, for example http://example.org/myapp/

My @ app.route decoders are for example @app.route('/')

for my application root ( http://example.org/myapp

) and @app.route('/subpage')

for subpages like http://example.org/myapp/subpage

.

In apache, it all "just worked" and my calls url_for()

created URLS that did the job.

Now my urls from url_for()

are of the form: href="/subpage"

which sends me to the domain root http://example.org/subpage

instead of what I wanted: href="./subpage"

which would lead me to http://example.org/myapp/subpage

.

For what it's worth, the relevant section from my Nginx config:

    location /myapp/ {
        proxy_redirect     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_set_header   X-Forwarded-Host $server_name;
        proxy_pass         http://127.0.0.1:8001/;
    }

      

I am serving an application with a cannon.

In a situation where it is located, visit http://example.org/myapp/

leads me to the root page of my Flask application, but the rest of me back in the URL domain level: http://example.org/subpage

.

I tried setting APPLICATION_ROOT to "/ myapp" but it doesn't seem to have any effect. What am I doing (horribly) wrong?

+3


source to share


2 answers


A solution can be found in this snippet (or at least a): http://flask.pocoo.org/snippets/35/



I'm still surprised that nothing is more elegant, but this will do for now.

+5


source


I know this is an old question, but I had the same problem and wanted something better than EricD's answer.

The solution is to use the _external

in flag url_for

and set the HOST header when passing the proxy to include the rest of the path:

So, in your flash app create a url using



url_for('index', _external=True)

      

And in your nginx config do the following:

location /myapp/ {
    ...
    proxy_set_header   Host $host/myapp;
    ...
}

      

+1


source







All Articles