2

I have a third party django app with it's own urls but they require a trailing slash. How can I support both with and without the slash?

Ryan Allen
  • 5,414
  • 4
  • 26
  • 33

1 Answers1

1
import re

from django.conf.urls import url, include

def optional_trailing_slash(urls):
   for url in urls[0].urlpatterns:
       url.regex = re.compile(url.regex.pattern.replace('/$', '/?$'))
   return urls

urlpatterns = [
   url(r'^', optional_trailing_slash(include('third_party_app.urls'))),
]
Ryan Allen
  • 5,414
  • 4
  • 26
  • 33
  • 1
    You probably want to avoid this, because it will make the documents available under both URIs, which will be penalized by search engines and might introduce subtle bugs in your application, if you have any client-side code. Did you check django's [APPEND_SLASH](https://docs.djangoproject.com/en/dev/ref/settings/#append-slash) setting? It automatically appends a trailing `/` and sends a redirect so both URIs work yet one is properly seen as an alias of the other. – spectras Sep 11 '17 at 23:41
  • 2
    Definitely valid considerations, thanks for commenting. The project I'm working on is an internal API so SEO won't be an issue. The front-end team asked for this support so that POST data isn't lost on the APPEND_SLASH redirect functionality. – Ryan Allen Sep 11 '17 at 23:54