35 lines
1.2 KiB
Python
35 lines
1.2 KiB
Python
from django.conf import settings
|
|
from django.http import HttpResponsePermanentRedirect
|
|
|
|
class SSLRedirectMiddleware:
|
|
"""
|
|
Middleware para redirigir:
|
|
1. HTTP a HTTPS.
|
|
2. Dominio sin `www` a dominio con `www`.
|
|
3. Añadir `/es/` si no está presente.
|
|
"""
|
|
def __init__(self, get_response):
|
|
self.get_response = get_response
|
|
|
|
def __call__(self, request):
|
|
host = request.get_host()
|
|
is_https = request.is_secure() or settings.DEBUG # Para entornos locales en DEBUG
|
|
|
|
# Redirigir a HTTPS si no está seguro
|
|
if not is_https:
|
|
url = request.build_absolute_uri().replace("http://", "https://")
|
|
return HttpResponsePermanentRedirect(url)
|
|
|
|
# Redirigir al dominio con `www`
|
|
if not host.startswith("www."):
|
|
new_host = f"www.{host}"
|
|
url = request.build_absolute_uri().replace(host, new_host)
|
|
return HttpResponsePermanentRedirect(url)
|
|
|
|
# Redirigir a `/es/` si no está incluido
|
|
if not request.path.startswith('/es/'):
|
|
url = f"https://{host}/es{request.get_full_path()}"
|
|
return HttpResponsePermanentRedirect(url)
|
|
|
|
return self.get_response(request)
|