A simple Django middleware that enforces a "no trailing slash" policy by permanently redirecting (301) any URL ending in a slash to its non-slashed version.
This is useful for SEO purposes to prevent duplicate content indexing.
- Performs a 301 Permanent Redirect.
- Preserves query strings.
- Ignores the root path (
/). - Allows configurable exclusion of URL prefixes (e.g.,
/admin/,/api/).
pip install bear-django-remove-trailing-slash- Add the middleware to your
MIDDLEWARElist insettings.py. It is recommended to place it before Django'sCommonMiddleware.
# settings.py
MIDDLEWARE = [
'remove_slash.middleware.RemoveTrailingSlashMiddleware',
# ... other middleware
]- (Optional) By default, the middleware ignores URLs starting with
/admin/. You can customize this by addingREMOVE_SLASH_IGNORE_PREFIXESto yoursettings.py.
# settings.py
REMOVE_SLASH_IGNORE_PREFIXES = ['/admin/', '/api/v1/']That's it! The middleware will now automatically handle redirects.