diff --git a/django/middleware/locale.py b/django/middleware/locale.py index 0867e3d60f..996b2d4c5b 100644 --- a/django/middleware/locale.py +++ b/django/middleware/locale.py @@ -1,7 +1,7 @@ "This is the locale selecting middleware that will look at accept headers" from django.conf import settings -from django.core.urlresolvers import (is_valid_path, get_resolver, +from django.core.urlresolvers import (is_valid_path, get_resolver, get_script_prefix, LocaleRegexURLResolver) from django.http import HttpResponseRedirect from django.utils.cache import patch_vary_headers @@ -45,9 +45,18 @@ class LocaleMiddleware(object): path_valid = is_valid_path("%s/" % language_path, urlconf) if path_valid: - language_url = "%s://%s/%s%s" % ( - request.scheme, request.get_host(), language, - request.get_full_path()) + script_prefix = get_script_prefix() + language_url = "%s://%s%s" % ( + request.scheme, + request.get_host(), + # insert language after the script prefix and before the + # rest of the URL + request.get_full_path().replace( + script_prefix, + '%s%s/' % (script_prefix, language), + 1 + ) + ) return self.response_redirect_class(language_url) if not (self.is_language_prefix_patterns_used() diff --git a/tests/i18n/patterns/tests.py b/tests/i18n/patterns/tests.py index 93284578b0..a4049fca13 100644 --- a/tests/i18n/patterns/tests.py +++ b/tests/i18n/patterns/tests.py @@ -3,7 +3,7 @@ from __future__ import unicode_literals import os from django.core.exceptions import ImproperlyConfigured -from django.core.urlresolvers import reverse, clear_url_caches +from django.core.urlresolvers import reverse, clear_url_caches, set_script_prefix from django.http import HttpResponsePermanentRedirect from django.middleware.locale import LocaleMiddleware from django.test import TestCase, override_settings @@ -290,6 +290,25 @@ class URLResponseTests(URLTestCaseBase): self.assertEqual(response.context['LANGUAGE_CODE'], 'pt-br') +class URLRedirectWithScriptAliasTests(URLTestCaseBase): + """ + #21579 - LocaleMiddleware should respect the script prefix. + """ + def setUp(self): + super(URLRedirectWithScriptAliasTests, self).setUp() + self.script_prefix = '/script_prefix' + set_script_prefix(self.script_prefix) + + def tearDown(self): + super(URLRedirectWithScriptAliasTests, self).tearDown() + # reset script prefix + set_script_prefix('') + + def test_language_prefix_with_script_prefix(self): + response = self.client.get('/prefixed/', HTTP_ACCEPT_LANGUAGE='en', SCRIPT_NAME=self.script_prefix) + self.assertRedirects(response, '%s/en/prefixed/' % self.script_prefix, target_status_code=404) + + class URLTagTests(URLTestCaseBase): """ Test if the language tag works.