【问题标题】:How do I automatically redirect a heroku app URL to my custom domain with Django?如何使用 Django 自动将 Heroku 应用程序 URL 重定向到我的自定义域?
【发布时间】:2017-06-25 04:59:02
【问题描述】:

我在example.herokuapp.com 有一个使用 django 的 heroku 应用程序。 我还有一个自定义域,指向这个heroku 应用程序example.com

我怎样才能让任何时候有人访问example.herokuapp.com,它会自动重定向到我在example.com 的自定义域?

我基本上只希望用户看到网址example.com,即使他们输入example.herokuapp.com

请记住,这是一个 django 应用程序。我可以将每条路由重定向到我的自定义域,但我想知道是否有更简单/更好的方法来做到这一点。

【问题讨论】:

    标签: python django redirect heroku


    【解决方案1】:

    简单的解决方案是使用 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 列表中。

    【讨论】:

    • 我正在尝试这个,但得到 `__init__() 需要 1 个位置参数,但给定了 2 个. How should I reference this in MIDDLEWARE` 设置?
    • 实际上从头开始,这不适用于 Django 1.11。它根本不是重定向。请注意,我的设置文件中有MIDDLEWAREMIDDLEWARE_CLASSES
    【解决方案2】:

    @rishubk 的回答已经过去很长时间了,我认为如果我对当前的 Django 3.x 和 4.x 版本(也许对于未来的版本)更正 CanonicalDomainMiddleware 会更好。

    在这里我是如何改变的,你可以找到:

    https://github.com/berkaymizrak/Resume-Django-Web-App/blob/main/resume/CanonicalDomainMiddleware.py

    正如我所见,基本的变化是 init 函数需要 2 个参数,如果你什么都不做而不是返回 None,你必须使用 return self.get_response...

    from django.shortcuts import redirect
    from django.core.exceptions import MiddlewareNotUsed
    from django.conf import settings
    
    
    class CanonicalDomainMiddleware(object):
    
        """Middleware that redirects to a canonical domain."""
    
        def __init__(self, get_response):
            self.get_response = get_response
            if settings.DEBUG or not settings.SITE_DOMAIN:
                raise MiddlewareNotUsed
    
        def __call__(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 self.get_response(request)
            # Check against the site domain.
            canonical_hostname = settings.SITE_DOMAIN.split(":", 1)[0]
            if hostname == canonical_hostname:
                return self.get_response(request)
            else:
                if request.is_secure():
                    canonical_url = "https://"
                else:
                    canonical_url = "http://"
                canonical_url += settings.SITE_DOMAIN + request.get_full_path()
                return redirect(canonical_url, permanent=True)
    

    【讨论】:

      猜你喜欢
      • 2017-01-19
      • 2021-03-04
      • 1970-01-01
      • 2013-08-27
      • 2019-11-24
      • 1970-01-01
      • 2019-02-26
      • 2018-04-16
      • 2018-09-11
      相关资源
      最近更新 更多