LoginSignup
2

More than 5 years have passed since last update.

異なるHostnameでのアクセスを正しいHostnameへリダイレクトする(Django)

Posted at

目的

  • www.example.com というホスト名でアクセスして欲しい。異なる場合はリダイレクトしたい。

case1

  • IPアドレスでアクセスされた場合は望ましくないので、www.example.comにリダイレクトしたい。

case2 (Heroku)

  • Herokuでは、任意のカスタムドメインを指定することができます。
  • ただし、カスタムドメインを適用してもオリジナルのHerokuDomainも有効のままになってしまいます。
  • つまり、「example.herokuapp.com」のようなホスト名は常に有効なままになるのですが、このホスト名のアクセスは望ましくありません。
  • Herokuのドキュメントでは、アプリケーションでリダイレクトしてね、と記述があります。

対応方法

  • lib/middleware.py を作成(ディレクトリ、ファイル名は任意です)
lib/middleware.py
from django.http import HttpResponsePermanentRedirect
from django.conf import settings

class RedirectCorrectHostname(object):
    """
    redirects to correct hostname if requested hostname and settings.CORRECT_HOST does not match
    (at heroku domain redirects to custom domain)
    """
    def process_request(self, request):
        if not getattr(settings, 'CORRECT_HOST', None):
            return None
        if request.get_host() == settings.CORRECT_HOST:
            return None

        return HttpResponsePermanentRedirect(
            '{scheme}://{host}{path}'.format(scheme=request.scheme,
                                             host=settings.CORRECT_HOST,
                                             path=request.get_full_path()))

(Gistにもあります)

  • projectame/settings.py に上記middlewareを記述 (下記はlib/middleware.py とした場合の例)
projectame/settings.py
MIDDLEWARE_CLASSES = [
    'lib.middleware.RedirectCorrectHostname',
...
  • projectame/settings.py に期待するホスト名を設定
projectame/settings.py
CORRECT_HOST = 'www.example.com'  # このホスト名以外のアクセスはリダイレクトする

確認

  • curlで確認
$ curl --head http://10.0.0.1/test
HTTP/1.1 301 Moved Permanently
Location: http://www.example.com/test
...

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2