0

I am developing a Flask app running on a sub-route of a server.

Here's a minimal version of the app:

from flask import *

app = Flask(__name__, root_path="/test")
app.config["APPLICATION_ROOT"] = "/test"

@app.route("/")
@app.route("/index")
def index():
    return url_for("index")

@app.route("/test")
def test():
    return url_for("test")

if __name__ == "__main__":
    app.run(port=5000, debug=True)

Here's the relevant part of /etc/nginx/nginx.conf:

http {
    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  localhost;

        location /test {
            return 302 /test/;
        }

        location /test/ {
            proxy_pass http://127.0.0.1:5000/;
        }
    }
}

This way, when I visit http://localhost/test/, the Flask application will get an incoming request at /, as proxied by nginx. This is configured at nginx level and cannot be changed, so what the application receives will always have the /test prefix truncated.

However I need url_for to generate URLs with that prefix. I am currently seeing /index at /test/, but what I expect is /test/index.

As shown in the code, APPLICATION_ROOT didn't work for me.

I have latest Flask (1.0.2) and dependencies.

iBug
  • 35,554
  • 7
  • 89
  • 134
  • See the duplicate, you need to use a `DispatcherMiddleware()` setup or put your routes in a blueprint. – Martijn Pieters Mar 14 '19 at 16:18
  • @MartijnPieters If I use either solution, my app will expect an actual URL of `//localhost/test/test/index` to trigger `app.route("/index")`, when it is currently `//localhost/test` (not expected to change). Nginx will truncate one `/test` and either the middleware or the blueprint will still expect another `/test` before the actual route. – iBug Mar 14 '19 at 16:22
  • I am pretty sure you can overload the decorator app.route, and not have to go to the wgsi serving your app, don 't know why that is the only answer accepted – E.Serra Mar 14 '19 at 16:50

0 Answers0