redirect and canonical tag
This commit is contained in:
parent
26064d749c
commit
b836d38e70
4 changed files with 50 additions and 0 deletions
29
hub/middleware.py
Normal file
29
hub/middleware.py
Normal file
|
@ -0,0 +1,29 @@
|
|||
from django.conf import settings
|
||||
from django.http import HttpResponseRedirect
|
||||
from urllib.parse import urlparse
|
||||
|
||||
|
||||
class PrimaryDomainRedirectMiddleware:
|
||||
def __init__(self, get_response):
|
||||
self.get_response = get_response
|
||||
# Parse the primary hostname from WEBSITE_URL
|
||||
self.primary_host = urlparse(settings.WEBSITE_URL).netloc
|
||||
|
||||
def __call__(self, request):
|
||||
# Skip redirects in DEBUG mode
|
||||
if settings.DEBUG:
|
||||
return self.get_response(request)
|
||||
|
||||
# Check if the host is different from the primary host
|
||||
if request.get_host() != self.primary_host:
|
||||
# Build the redirect URL
|
||||
scheme = "https" # Always use HTTPS for redirects
|
||||
path = request.get_full_path() # Includes query string
|
||||
redirect_url = f"{scheme}://{self.primary_host}{path}"
|
||||
|
||||
# Use 301 permanent redirect
|
||||
response = HttpResponseRedirect(redirect_url)
|
||||
response.status_code = 301
|
||||
return response
|
||||
|
||||
return self.get_response(request)
|
Loading…
Add table
Add a link
Reference in a new issue