Trailing slash behavior helps Flask decide if a URL should end with a slash or not. It makes your web app handle URLs more flexibly and avoid errors.
Trailing slash behavior in Flask
@app.route('/path/') # redirects /path to /path/ @app.route('/path') # 404 on /path/
Adding a trailing slash in the route means Flask will redirect URLs without the slash to the one with it.
Not adding a trailing slash means Flask will return 404 if the slash is added in the URL.
@app.route('/hello/') def hello(): return 'Hello with slash!' # Accessing '/hello' redirects to '/hello/'
@app.route('/world') def world(): return 'Hello without slash!' # Accessing '/world/' returns 404 error
This Flask app has two routes: one with a trailing slash and one without. Visiting '/greet' will redirect to '/greet/'. Visiting '/bye/' will cause a 404 error because the route does not have a trailing slash.
from flask import Flask app = Flask(__name__) @app.route('/greet/') def greet_slash(): return 'Greet with slash!' @app.route('/bye') def bye_no_slash(): return 'Bye without slash!' if __name__ == '__main__': app.run(debug=True)
Flask's trailing slash behavior helps keep URLs consistent and user-friendly.
Use trailing slashes for routes that represent folders or collections.
Use no trailing slash for routes that represent single items or actions.
Trailing slash in Flask routes controls URL redirection and 404 errors.
Routes with trailing slash redirect URLs without it to the slash version.
Routes without trailing slash do not accept URLs with an extra slash.