Trailing slash triggers 404 in Flask path rule

Your /users route is missing a trailing slash, which Werkzeug interprets as an explicit rule to not match a trailing slash. Either add the trailing slash, and Werkzeug will redirect if the url doesn’t have it, or set strict_slashes=False on the route and Werkzeug will match the rule with or without the slash.

@app.route('/users/')
@app.route('/users/<path:path>')
def users(path=None):
    return str(path)

c = app.test_client()
print(c.get("https://stackoverflow.com/users"))  # 302 MOVED PERMANENTLY (to /users/)
print(c.get('/users/'))  # 200 OK
print(c.get('/users/test'))  # 200 OK
@app.route("https://stackoverflow.com/users", strict_slashes=False)
@app.route('/users/<path:path>')
def users(path=None):
    return str(path)

c = app.test_client()
print(c.get("https://stackoverflow.com/users"))  # 200 OK
print(c.get('/users/'))  # 200 OK
print(c.get('/users/test'))  # 200 OK

You can also set strict_slashes for all URLs.

app.url_map.strict_slashes = False

However, you should avoid disabling strict slashes in most cases. The docs explain why:

This behavior allows relative URLs to continue working even if the trailing slash is omitted, consistent with how Apache and other servers work. Also, the URLs will stay unique, which helps search engines avoid indexing the same page twice.

Leave a Comment