Django - 从URL中删除www

时间:2014-10-14 11:27:22

标签: django apache .htaccess no-www

我已将此添加到我的.htacces

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]

然后尝试联系www.example.com将我重定向到:

http://example.com/example/wsgi.py/

因为我的WSGIScriptAlias / home/www/example.com/example/wsgi.py中有httpd.conf指令,当然我收到404错误。

最后,我通过在urls.py中添加下一行来设法修复

url(r'^example/wsgi.py/$', index),(因此重定向到主页)

但我不太确定这是正确的做法(因为当我尝试访问example.com时,我发现网络浏览器会快速更改地址www.example.com,然后再转到{ {1}})

如果有人会问,是的,我已经看过this,但这也没有帮助我,因为浏览器会出现网址递归问题(example.com/example.com/example.com/example.com/ example.com ...)

编辑:文件夹结构

这是我的文件夹结构:

example.com

4 个答案:

答案 0 :(得分:3)

我知道这已经回复了一段时间,但要添加上面给出的答案

host.startswith('www.')

它更具可读性,你也应该使用永久重定向来为浏览器提供正确的响应标题。

from django import http

class NoWWWRedirectMiddleware(object):
    def process_request(self, request):
        host = request.get_host()
        if host.startswith('www.'):
            if request.method == 'GET':  # if wanna be a prefect REST citizen, consider HEAD and OPTIONS here as well
                no_www_host = host[4:]
                url = request.build_absolute_uri().replace(host, no_www_host, 1)
                return http.HttpResponsePermanentRedirect(url)

答案 1 :(得分:1)

我发现使用Apache mod_rewrite config实现中间件的无www重定向要简单得多。

您链接到的中间件看起来像是诀窍。我猜你的问题来自Apache配置 - 请确保删除所有mod_rewrite命令(Rewrite*东西),然后重新启动apache服务器(参考Apache docs但是检查你的操作系统,可能是特异性的)。

您应该只进行一次额外的调整:确保您不会重定向任何POST请求,因为这可能会导致数据丢失(正切参考:Why doesn't HTTP have POST redirect?)。

无论如何,这是我使用的,对我来说效果很好:

from django.http import HttpResponseRedirect

class NoWWWRedirectMiddleware(object):
    def process_request(self, request):

    if request.method == 'GET':  # if wanna be a prefect REST citizen, consider HEAD and OPTIONS here as well
        host = request.get_host()
        if host.lower().find('www.') == 0:
            no_www_host = host[4:]
            url = request.build_absolute_uri().replace(host, no_www_host, 1)
            return HttpResponseRedirect(url)

要使用它,请将文件放在某处,可能是mysite/mysite/middleware.py。 然后在settings.py

中确保它正常运行
MIDDLEWARE_CLASSES = (
    'mysite.middleware.NoWWWRedirectMiddleware',
    # ... other middleware ...

如果MIDDLEWARE_CLASSES中没有settings.py,则从here in the Django docs复制默认值但让您查看正确版本的Django,1.7中有一些更改!

答案 2 :(得分:0)

这个Apache配置适用于我:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ http://example.com$1 [R=301,L]

WSGIScriptAlias / /home/www/example.com/example/wsgi.py
WSGIPythonPath /home/www/example.com/example

<Directory /home/www/example.com/example>
  <Files wsgi.py>
    Require all granted
  </Files>
</Directory>

答案 3 :(得分:0)

与Django 1.11+样式中间件一起使用的修改版本:

from django.http import HttpResponsePermanentRedirect

class NoWWWRedirectMiddleware:
    def __init__(self, get_response=None):
        self.get_response = get_response

    def __call__(self, request):
        response = self.process_request(request)
        return response or self.get_response(request)

    def process_request(self, request):
        host = request.get_host()
        if host.startswith('www.'):
            if request.method == 'GET':
                no_www = host[4:]
                url = request.build_absolute_uri().replace(host, no_www, 1)
                    return HttpResponsePermanentRedirect(url)