Created
January 8, 2020 18:50
-
-
Save Owanesh/d33db70e1b16ce87499833b997038136 to your computer and use it in GitHub Desktop.
Remove /lang/ path for settings.LANGUAGE_CODE
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf import settings | |
from django.urls.base import is_valid_path | |
from django.http import HttpResponsePermanentRedirect | |
from django.middleware.locale import LocaleMiddleware | |
from django.utils.cache import patch_vary_headers | |
class RemoveDefaultLanguagePath(LocaleMiddleware): | |
def process_response(self, request, response): | |
language = get_language() | |
if (response.status_code == 404 and request.path_info.startswith('/'+settings.LANGUAGE_CODE+'/')): | |
urlconf = getattr(request, 'urlconf', None) | |
language_path = request.path_info[3:] | |
if is_valid_path(language_path, urlconf): | |
language_url = "%s://%s%s" % ( | |
request.is_secure() and 'https' or 'http', | |
request.get_host(), language_path) | |
return HttpResponsePermanentRedirect(language_url) | |
patch_vary_headers(response, ('Accept-Language',)) | |
if 'Content-Language' not in response: | |
response['Content-Language'] = language | |
return response |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
LANGUAGE_CODE='en' | |
MIDDLEWARE = [ | |
... | |
"myapp.middleware.RemoveDefaultLanguagePath", | |
... | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Remove default /lang/ path from urls
Make your site SEO Friendly with 301 redirects
It's useful to redirect (301) urls like
/it/dont-eat-pizza-with-pineapple
to/dont-eat-pizza-with-pineapple
if your default language issetting.LANGUAGE_CODE='it'
it checks if
/dont-eat-pizza-with-pineapple
is a valid url, then redirects, else stays on pageWhen it's really useful?
This middleware is PoC for a "bug"
Assume to have a site with multilanguage
en/ru/de/it
and after a year you want change all links of main language (example:it
)Now google and other spiders knows your old url, like
it/about-us
but now you want to change it to/about-us
because you don't want language-prefix path for default language anymore.After set
prefix_default_language=False
into youri18n_patterns
aturls.py
, you need to teach to google where old page are.And what's better than a 301 redirect?
If you like it, feel free to star ⭐ or fork my code