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.
You can prevent Django from automatically appending slash to urls by putting this line in your settings file:
But I think a better way would be to use
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: