2017-06-25 11 views
-1

example.herokuapp.comにdjangoを使用しているherokuアプリがあります。 は、私はまた、誰かがexample.herokuapp.comに行くの任意の時間は、それが自動的にexample.comで私のカスタムドメインにリダイレクトするようにどのように私はそれを行うことができますexample.comリダイレクトdjango heroku app

でこのHerokuのアプリを指すカスタムドメインを持っていますか?

は、私は基本的にのみ、ユーザーがexample.herokuapp.com

で、これはDjangoのアプリであることに留意してください入力した場合でも、URL example.comを見てみたいです。すべてのルートをカスタムドメインにリダイレクトすることができましたが、これを行うためのより簡単で良い方法があるかどうかは疑問です。

編集:私は、人々がdownvotedので、質問が本当に悪いか何かだったと思いますが、それが問題だったと私は、私は簡単な解決策はただでDjangoのアプリにミドルウェアを追加することです

答えて

0

下に掲載解決策を見つけましたprocess_request()ルートが要求されるたびに呼び出される関数。私はここからのコードだ :ここ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リストにこのクラスを追加してください。