我在example.herokuapp.com
使用django有一个heroku应用程序。
我还有一个自定义域,指向example.com
我该如何制作,以便每当有人前往example.herokuapp.com
时,它会自动重定向到example.com
的自定义域名?
我基本上只希望用户看到网址example.com
即使他们输入example.herokuapp.com
请记住,这是一款django应用。我可以将每个路由重定向到我的自定义域,但我想知道是否有更容易/更好的方法来执行此操作。
答案 0 :(得分:0)
简单的解决方案是只使用process_request()
函数将中间件添加到django应用程序,每次请求路由时都会调用该函数。
我从这里得到了代码:https://github.com/etianen/django-herokuapp/blob/master/herokuapp/middleware.py
这是一个可以添加的文件middelware.py:
from django.shortcuts import redirect
from django.core.exceptions import MiddlewareNotUsed
from django.conf import settings
SITE_DOMAIN = "example.com"
class CanonicalDomainMiddleware(object):
"""Middleware that redirects to a canonical domain."""
def __init__(self):
if settings.DEBUG or not SITE_DOMAIN:
raise MiddlewareNotUsed
def process_request(self, request):
"""If the request domain is not the canonical domain, redirect."""
hostname = request.get_host().split(":", 1)[0]
# Don't perform redirection for testing or local development.
if hostname in ("testserver", "localhost", "127.0.0.1"):
return
# Check against the site domain.
canonical_hostname = SITE_DOMAIN.split(":", 1)[0]
if hostname != canonical_hostname:
if request.is_secure():
canonical_url = "https://"
else:
canonical_url = "http://"
canonical_url += SITE_DOMAIN + request.get_full_path()
return redirect(canonical_url, permanent=True)
最后,请务必将此类添加到settings.py文件中的MIDDLEWARE_CLASSES列表中。