2014-07-07 115 views
2

在Django的urls.py文件中,如何編寫url重定向以便login.domain.com執行301重定向到domain.com/login?我正在尋找一種方法將一個子域重定向到一個url。我意識到這可以使用ningx來處理,但是,我希望能夠在Django中進行維護。django:將子域重定向到另一個url

回答

1

3rd party apps通常會將此功能放入中間件中,並使用process_request鉤子來負責子域的識別,然後執行適當的重定向。

實例顯示從Django的子域

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) 
+0

定製的中間件和應用process_request我在哪裏把重定向使login.domain.com重定向到domain.com/login? – wwwuser

+0

@www你可以把它放在'process_request'中 – dm03514

相關問題