django:将子域重定向到另一个url

时间:2014-07-07 16:22:29

标签: django subdomain

在urls.py文件中的Django中,如何编写URL重定向,以便login.domain.com执行301重定向到domain.com/login?我正在寻找一种方法将子域名重定向到网址。我意识到这可以使用ningx来处理,但是,我希望能够在Django中维护它。

1 个答案:

答案 0 :(得分:2)

3rd party apps通常将此功能放入中间件并使用process_request挂钩来处理子域重新定义,然后执行适当的重定向。

显示自定义中间件并使用django-subdomains中的process_request

的示例
class SubdomainMiddleware(object):
    """
    A middleware class that adds a ``subdomain`` attribute to the current request.
    """
    def get_domain_for_request(self, request):
        """
        Returns the domain that will be used to identify the subdomain part
        for this request.
        """
        return get_domain()

    def process_request(self, request):
        """
        Adds a ``subdomain`` attribute to the ``request`` parameter.
        """
        domain, host = map(lower,
            (self.get_domain_for_request(request), request.get_host()))

        pattern = r'^(?:(?P<subdomain>.*?)\.)?%s(?::.*)?$' % re.escape(domain)
        matches = re.match(pattern, host)

        if matches:
            request.subdomain = matches.group('subdomain')
        else:
            request.subdomain = None
            logger.warning('The host %s does not belong to the domain %s, '
                'unable to identify the subdomain for this request',
                request.get_host(), domain)