Django – remove the trailing slash from 'sitemap.xml/'

252 Views Asked by At

I am using Django's sitemap framework and have a sitemap index. My urls file looks like this:

urls = [
    path('', include('movies.urls')),
    path('', include('accounts.urls')),
    ...
    path('admin/', admin.site.urls),
]

urlpatterns = i18n_patterns(*urls, prefix_default_language=True,)

sitemaps = {
    'main': MainSitemap,
    'movies': MoviesSitemap,
}

urlpatterns.extend([
    path('sitemap.xml', views.index, {'sitemaps': sitemaps}),
    path('sitemap-<section>.xml', views.sitemap, {'sitemaps': sitemaps},
     name='django.contrib.sitemaps.views.sitemap'),
])

This is implemented in accordance with the recommendations in the documentation of Django.

The problem is that I always get 404 when trying to access my sitemap index: example.com/sitemap.xml. This occurs because a redirect occurs automatically to the non-existent example.com/sitemap.xml/ URL with a trailing slash.

How can I avoid a slash being appended to the .xml sitemap file? I have tried using re_path but to no avail.

2

There are 2 best solutions below

3
On

You can prevent Django from automatically appending slash to urls by putting this line in your settings file:

APPEND_SLASH = False

But I think a better way would be to use

path('sitemap.xml/', views.index, {'sitemaps': sitemaps}),

in urlpatterns. I'm not sure if the second solution works, but it should.


Update:

As can be seen in the other answer you can use re_path with optional trailing slash:

from django.urls import re_path

re_path(r'sitemap.xml/?$', views.index, {'sitemaps': sitemaps}),
3
On

You can use re_path instead of path to use regular expression in your url pattern. Use ? sign in your url like this:

from django.urls import re_path
re_path(r'sitemap.xml/?$', views.appmain, {'sitemaps': sitemaps}),