Trailing URL Slashes in Django
Note: Web browsers aggressively cache past URLs and will often automatically add a trailing slash
/ as a result. You may need to clear all your cookies or try a different web browser than your default to fully see this change in action.
For example, within the Admin of any Django project, if you wanted to see "Users" the full route is
http://127.0.0.1:8000/admin/auth/user/ but if you instead typed into your web browser
127.0.0.1:8000/admin/auth/user (notice no
/ at the end there!), it automatically redirects to
And if you look at the logs in your command line, you'll see something like the following which shows a 301 redirect was perfored my Django to append the slash.
[19/Mar/2022 15:49:44] "GET /admin/auth/user HTTP/1.1" 301 0 [19/Mar/2022 15:49:44] "GET /admin/auth/user/ HTTP/1.1" 200 6596
Now let's turn off the default setting to confirm that Django is performing this action for us. Within your
settings.py file, add the following line at the bottom:
# settings.py APPEND_SLASH = False
The local Django webserver will automatically restart to reflect the changes. Try again to refresh the web page for the User section of the admin without the trailing slash:
The result? A 404 page! Because we've turned
You can see this in the logs as well.
[19/Mar/2022 15:53:41] "GET /admin/auth/user HTTP/1.1" 404 3869
Therefore as a practical matter make sure that you include a
/ at the end of your Django URLs. You don't have to but absent this nice built-in feature--or Chrome--you'll receive unexpected errors.
Special thanks to Carlton Gibson for help on this topic and suggesting the Admin example.