I have a flask app which I want to host it on a subfolder of a website, like example.com/cn
.
I configured my nginx like
location /cn {
proxy_pass http://localhost:8000/;
}
So if I access example.com/cn
, It will redirect to the index page of flask.
However, I have wrote the routes of other pages on flask like app.route('/a')
. So if I click the link of page a
, the URI is example.com/a
, then nginx
cannot redirect it to the right page.
I think I can rewrite all the routes on flask like app.route('/cn/a')
, but it’s complex. And if someday I want to deploy it on example.com/en
, I think I need to rewrite all the routes again.
Does anyone have other methods?
4
Answers
I have found a perfect solution here.
You can use
url_prefix="/cn"
option when defining blueprints:https://flask.palletsprojects.com/en/2.0.x/blueprints/#nesting-blueprints
You need to add APPLICATION_ROOT params to your flask app:
if you need to host more than one application on your server, you can configure nginx to redirect all request to your specific flask app served by gunicorn like this. (it is not necessary if your server hosts only one application) Find out more about gunicorn and nginx here: https://docs.gunicorn.org/en/stable/deploy.html
serve flask app with gunicorn:
A complete exmaple here: https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-gunicorn-and-nginx-on-ubuntu-18-04
If you are using flask_restful instead, you can specify the root path also in the following way:
Suppose you want to host your application under
/api
with Nginx.First, config your URL prefix to
location
andX-Forwarded-Prefix
header:Then use Werkzeug’s
ProxyFix
middleware to tell Flask it’s behind a proxy:See also:
P.S. If you are using OpenAPI, also remember to update the
servers
field to indicate the location of the server.