我需要将所有来自www.mysite.com
的请求重定向到mysite.com
我找到了solution in rails,但我怎么能在django / python中做到这一点?
我可以解决的唯一解决方案是由GoDaddy上的主持人发布的,如上所述。好像我无法通过GoDaddy的DNS管理器解决这类问题。
任何提示或想法?
提前致谢。
答案 0 :(得分:5)
在[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
列表。PREPEND_WWW = True
此中间件基于Django's CommonMiddleware。
答案 1 :(得分:0)
解决了这个问题:
from django.http import HttpResponsePermanentRedirect
class WWWRedirectMiddleware(object):
def process_request(self, request):
if request.META['HTTP_HOST'].startswith('www.'):
return HttpResponsePermanentRedirect('http://mysite.com')