简体   繁体   English

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

[英]How do I automatically redirect a heroku app URL to my custom domain with Django?

I have a heroku app using django at example.herokuapp.com .我在example.herokuapp.com有一个使用 django 的 heroku 应用程序。 I also have a custom domain that points to this heroku app at example.com我还有一个自定义域指向example.com上的这个 heroku 应用程序

How can I make it so that any time someone goes to example.herokuapp.com , it automatically redirects to my custom domain at example.com ?我怎样才能让它在任何时候有人去example.herokuapp.com时,它会自动重定向到我在example.com的自定义域?

I essentially only want users to see the url example.com even if they type in example.herokuapp.com我基本上只希望用户看到 url example.com ,即使他们输入example.herokuapp.com

Keep in mind that this is a django app.请记住,这是一个 django 应用程序。 I could redirect every route to my custom domain, but I am wondering if there is any easier/better way to do this.我可以将每条路由重定向到我的自定义域,但我想知道是否有更简单/更好的方法来做到这一点。

The simple solution is to just add middleware to the django app with a process_request() function that will be called everytime a route is requested. 一种简单的解决方案是仅使用一个process_request()函数将中间件添加到django应用中,该函数将在每次请求路由时调用。 I got the code from here: https://github.com/etianen/django-herokuapp/blob/master/herokuapp/middleware.py 我从这里获得了代码: https : //github.com/etianen/django-herokuapp/blob/master/herokuapp/middleware.py

Here is a file middelware.py that can be added: 这是可以添加的文件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)

Lastly, be sure to add this class to the MIDDLEWARE_CLASSES list in the settings.py file. 最后,确保将此类添加到settings.py文件的MIDDLEWARE_CLASSES列表中。

It has been long time after @rishubk 's answer and I thought it can be better if I mention corrected CanonicalDomainMiddleware for currently Django 3.x and 4.x versions (and maybe for future ones). @rishubk的回答已经很长时间了,我认为如果我为当前的 Django 3.x 和 4.x 版本(也许对于未来的版本)提及更正的CanonicalDomainMiddleware会更好。

Here how I changed, you can find:在这里我如何改变,你可以找到:

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

As I see the basic changes are init function takes 2 arguments and you must use return self.get_response... if you want to do nothing instead of returning None.正如我所看到的,基本的变化是初始化函数需要 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM