python - 如何使用 Django 自动将 heroku 应用程序 URL 重定向到我的自定义域?

标签 python django redirect heroku

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

的这个 heroku 应用程序

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

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

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

最佳答案

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

关于python - 如何使用 Django 自动将 heroku 应用程序 URL 重定向到我的自定义域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44743336/

相关文章:

Python Scrapy 不断返回 "Invalid Syntax"

php - 创建类似 Wiki 的 Web 应用程序的基础知识?

Django 1.2.4 CSRF 验证失败

redirect - Backbone.JS "sync"方法中处理 HTTP 302 错误和重定向

发布表单数据时linuxcurl 301重定向

python - django-crispy-forms 在同一行上有字段和按钮

python - 如何在python中实现 "cumdot"

python - Django ModelForm 不保存数据

c - 使用 fputc 通过管道写入

python - 如何在 Pytorch 中检查模型是否处于训练或评估模式?