Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用Django自动将heroku应用程序URL重定向到我的自定义域?_Python_Django_Redirect_Heroku - Fatal编程技术网

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

我基本上只希望用户看到url
example.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。这根本不是重定向。请注意,我的设置文件中既有
中间件
也有
中间件类