Python 如何使用Django自动将heroku应用程序URL重定向到我的自定义域?
我在Python 如何使用Django自动将heroku应用程序URL重定向到我的自定义域?,python,django,redirect,heroku,Python,Django,Redirect,Heroku,我在example.herokuapp.com上有一个使用django的heroku应用程序。 我还有一个自定义域,指向example.com 我如何使它在任何时候有人进入example.herokuapp.com,它都会自动重定向到我的自定义域example.com 我基本上只希望用户看到urlexample.com,即使他们键入example.herokuapp.com 请记住,这是一个django应用程序。我可以将每条路由重定向到我的自定义域,但我想知道是否有更简单/更好的方法来实现这一点
example.herokuapp.com
上有一个使用django的heroku应用程序。
我还有一个自定义域,指向example.com
我如何使它在任何时候有人进入example.herokuapp.com
,它都会自动重定向到我的自定义域example.com
我基本上只希望用户看到urlexample.com
,即使他们键入example.herokuapp.com
请记住,这是一个django应用程序。我可以将每条路由重定向到我的自定义域,但我想知道是否有更简单/更好的方法来实现这一点 简单的解决方案是,只需将中间件添加到django应用程序中,使用
process\u request()
函数,每次请求路由时都会调用该函数。
我从这里得到了密码:
以下是可以添加的文件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\u CLASSES列表中。我正在尝试此操作,但获取`\u init\uuuu()需要1个位置参数,但给出了2个
。我应该如何在
MIDDLEWARE`settings中引用它?事实上,这不适用于Django 1.11。这根本不是重定向。请注意,我的设置文件中既有中间件
也有中间件类
。