Skip to content

Instantly share code, notes, and snippets.

@Owanesh
Created January 8, 2020 18:50
Show Gist options
  • Save Owanesh/d33db70e1b16ce87499833b997038136 to your computer and use it in GitHub Desktop.
Save Owanesh/d33db70e1b16ce87499833b997038136 to your computer and use it in GitHub Desktop.
Remove /lang/ path for settings.LANGUAGE_CODE
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
LANGUAGE_CODE='en'
MIDDLEWARE = [
...
"myapp.middleware.RemoveDefaultLanguagePath",
...
]
@Owanesh
Copy link
Author

Owanesh commented Jan 8, 2020

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 is setting.LANGUAGE_CODE='it'

it checks if /dont-eat-pizza-with-pineapple is a valid url, then redirects, else stays on page

When 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 your i18n_patterns at urls.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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment