Kaj Kandler
Kaj Kandler

Reputation: 328

gunicorn + SCRIPT_NAME + flask (behind nginx)

I'm trying to deploy a gunicorn + flask app behind nginx with a path context (https://example.com/my-app)

The app runs fine locally with gunicorn + flask, setting the environment variable "SCRIPT_NAME" for the gunicorn runtime (actually a launch config in VS Code).

            "env": {
                "SCRIPT_NAME": "/my-app",

Then request.script_name becomes /my-app, as expected.

When I try to set the SCRIPT_NAME as a header in nginx

location /my-app/ {
                  include proxy_params;
                  proxy_set_header SCRIPT_NAME "/my-app";
                  proxy_pass http://localhost:5000;
          }

I can see the Script-Name: /my-app among the request.headers in the flask app

However, the request.script_name is empty and so all url_for(...) fail to work properly.

P.S.: I tried to set the env variable for gunicorn in the service descriptor, but in the (access) logs it does not show up. Anyways, the header solutions seems more appropriate, because it keeps the prefix in the place where I mount it into the rest of the server.

Upvotes: 1

Views: 767

Answers (1)

Kaj Kandler
Kaj Kandler

Reputation: 328

For what it is worth. I found my problem and the solution.

The SCRIPT_NAME header was overwritten by the

proxy_set_header X-Forwarded-Prefix /;

which was hiding in the proxy_params include file.

Removing this prefix led to gunicorn setting the correct header in flask and flask's url_for() behaving as expected.

Upvotes: 1

Related Questions