| | 1 | from django.core import urlresolvers |
|---|
| | 2 | from django import http |
|---|
| | 3 | |
|---|
| | 4 | class SmartSlashMiddleware(object): |
|---|
| | 5 | """ |
|---|
| | 6 | If the initial response is 404, and the initial path doesn't end with a slash, |
|---|
| | 7 | a new URL is formed by appending a slash. |
|---|
| | 8 | If the new URL is found in urlpatterns, then an HTTP-redirect to the new URL is returned. |
|---|
| | 9 | """ |
|---|
| | 10 | |
|---|
| | 11 | def process_response(self, request, response): |
|---|
| | 12 | path = request.path |
|---|
| | 13 | if response.status_code == 404 and path[-1] != '/': |
|---|
| | 14 | newpath = path + '/' |
|---|
| | 15 | try: |
|---|
| | 16 | urlresolvers.resolve(newpath) |
|---|
| | 17 | except urlresolvers.Resolver404: |
|---|
| | 18 | pass |
|---|
| | 19 | else: |
|---|
| | 20 | newurl = http.build_url(request, newpath) |
|---|
| | 21 | response = http.HttpResponsePermanentRedirect(newurl) |
|---|
| | 22 | return response |