【发布时间】:2012-09-27 08:44:21
【问题描述】:
我需要将来自www.mysite.com 的所有请求重定向到mysite.com
我找到了solution in rails,但是如何在 Django/Python 中做到这一点?
我能找到的唯一解决方案是由 GoDaddy 上的版主发布的。似乎我无法通过 GoDaddy 的 DNS Manager 解决此类问题。
【问题讨论】:
标签: python django heroku redirect dns
我需要将来自www.mysite.com 的所有请求重定向到mysite.com
我找到了solution in rails,但是如何在 Django/Python 中做到这一点?
我能找到的唯一解决方案是由 GoDaddy 上的版主发布的。似乎我无法通过 GoDaddy 的 DNS Manager 解决此类问题。
【问题讨论】:
标签: python django heroku redirect dns
解决了这个问题:
from django.http import HttpResponsePermanentRedirect
class WWWRedirectMiddleware(object):
def process_request(self, request):
if request.META['HTTP_HOST'].startswith('www.'):
return HttpResponsePermanentRedirect('http://example.com')
【讨论】:
在[PROJECT_NAME]/middleware.py 中创建自己的中间件,如下所示:
from django.conf import settings
from django.http import HttpResponsePermanentRedirect
from django.utils.deprecation import MiddlewareMixin
class RemoveWWWMiddleware(MiddlewareMixin):
"""
Based on the REMOVE_WWW setting, this middleware removes "www." from the
start of any URLs.
"""
def process_request(self, request):
host = request.get_host()
if settings.REMOVE_WWW and host and host.startswith('www.'):
redirect_url = '%s://%s%s' % (
request.scheme, host[4:], request.get_full_path()
)
return HttpResponsePermanentRedirect(redirect_url)
然后,在你项目的settings.py:
REMOVE_WWW = True
[PROJECT_NAME].middleware.RemoveWWWMiddleware 添加到MIDDLEWARE 列表中,在 Django 的 SecurityMiddleware 之后,最好在 Django 的 Common Middleware 之前。PREPEND_WWW = True
此中间件基于Django's CommonMiddleware。
【讨论】: