如何在Django下将domain.com重定向到WWW.domain.com?

时间:2022-12-04 08:15:38

How do I go about redirecting all requests for domain.com/... to www.domain.com/... with a 301 in a django site?

如何在django网站上将301的所有请求重定向到www.domain.com / ...并将其重定向到www.domain.com / ...

Obviously this can't be done in urls.py because you only get the path part of the URL in there.

显然这不能在urls.py中完成,因为你只在那里获得了URL的路径部分。

I can't use mod rewrite in .htaccess, because .htaccess files do nothing under Django (I think).

我不能在.htaccess中使用mod重写,因为.htaccess文件在Django下没有任何作用(我认为)。

I'm guessing something in middleware or apache conf?

我猜中间件或apache conf中的东西?

I'm running Django on a Linux server with Plesk, using mod WSGI

我正在使用mod WSGI在Plesk的Linux服务器上运行Django

6 个解决方案

#1


18  

The WebFaction discussion someone pointed out is correct as far as the configuration, you just have to apply it yourself rather than through a control panel.

有人指出的WebFaction讨论对于配置来说是正确的,你只需要自己应用它而不是通过控制面板。

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

Put in .htaccess file, or in main Apache configuration in appropriate context. If inside of a VirtualHost in main Apache configuration, your would have ServerName be www.example.com and ServerAlias be example.com to ensure that virtual host handled both requests.

放入.htaccess文件,或在适当的上下文中的主Apache配置中。如果在主Apache配置中的VirtualHost内,您将ServerName为www.example.com,ServerAlias为example.com,以确保虚拟主机处理这两个请求。

If you don't have access to any Apache configuration, if need be, it can be done using a WSGI wrapper around the Django WSGI application entry point. Something like:

如果您无权访问任何Apache配置,如果需要,可以使用围绕Django WSGI应用程序入口点的WSGI包装器来完成。就像是:

import django.core.handlers.wsgi
_application = django.core.handlers.wsgi.WSGIHandler()

def application(environ, start_response):
  if environ['HTTP_HOST'] != 'www.example.com':
    start_response('301 Redirect', [('Location', 'http://www.example.com/'),])
    return []
  return _application(environ, start_response)

Fixing this up to include the URL within the site and dealing with https is left as an exercise for the reader. :-)

修复此问题以在网站中包含URL并处理https是留给读者的练习。 :-)

#2


15  

The PREPEND_WWW setting does just that.

PREPEND_WWW设置就是这样做的。

#3


3  

There is a lightweight way to do that involving VirtualHosts and mod_alias Redirect directive. You can define two VirtualHosts, one holding the redirect and another holding the site configuration:

有一种轻量级方法可以实现VirtualHosts和mod_alias Redirect指令。您可以定义两个VirtualHost,一个包含重定向,另一个包含站点配置:

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / http://www.example.com/
</VirtualHost>

<VirtualHost *:80>
    ServerName www.example.com
    # real site configuration
</VirtualHost>

And that will do the job.

这将完成这项工作。

#4


0  

A full thread about the issue exists here http://forum.webfaction.com/viewtopic.php?id=1516

这里存在关于该问题的完整主题http://forum.webfaction.com/viewtopic.php?id=1516

#5


0  

This also can be done with a middleware.

这也可以用中间件完成。

Some examples:

一些例子:

This is a better version of snippet-510:

这是一个更好的snippet-510版本:

class UrlRedirectMiddleware(object):
    """
    This middleware lets you match a specific url and redirect the request to a
    new url. You keep a tuple of (regex pattern, redirect) tuples on your site
    settings, example:

    URL_REDIRECTS = (
        (r'(https?)://(www\.)?sample\.com/(.*)$', r'\1://example.com/\3'),
    )
    """
    def process_request(self, request):
        full_url = request.build_absolute_uri()
        for url_pattern, redirect in settings.URL_REDIRECTS:
            match = re.match(url_pattern, full_url)
            if match:
                return HttpResponsePermanentRedirect(match.expand(redirect))

#6


0  

I've tried Graham's solution but can't get it to work (even if the simplest case of http (not https) without any path. I'm not experienced with wsgi as you can probably guess and all help is deeply appreciated.

我已经尝试了格雷厄姆的解决方案,但无法让它工作(即使最简单的情况是http(而不是https)没有任何路径。我没有经验wsgi,因为你可能猜到并且所有的帮助都深表赞赏。

Here's my attempt (redirecting from www.olddomain.com to www.newdomain.com). When I try to deploy it, trying to reach www.olddomain.com results in a error ("Can't reach this page"):

这是我的尝试(从www.olddomain.com重定向到www.newdomain.com)。当我尝试部署它时,尝试访问www.olddomain.com会导致错误(“无法访问此页面”):

from django.core.wsgi import get_wsgi_application

_application = get_wsgi_application()

def application(environ, start_response):
  if environ['HTTP_HOST'][:21] == 'www.olddomain.com':
    start_response('301 Redirect', [('Location', 'http://www.newdomain.com/'),])
  return []

  return _application(environ, start_response)

Thank you for your help

感谢您的帮助

#1


18  

The WebFaction discussion someone pointed out is correct as far as the configuration, you just have to apply it yourself rather than through a control panel.

有人指出的WebFaction讨论对于配置来说是正确的,你只需要自己应用它而不是通过控制面板。

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

Put in .htaccess file, or in main Apache configuration in appropriate context. If inside of a VirtualHost in main Apache configuration, your would have ServerName be www.example.com and ServerAlias be example.com to ensure that virtual host handled both requests.

放入.htaccess文件,或在适当的上下文中的主Apache配置中。如果在主Apache配置中的VirtualHost内,您将ServerName为www.example.com,ServerAlias为example.com,以确保虚拟主机处理这两个请求。

If you don't have access to any Apache configuration, if need be, it can be done using a WSGI wrapper around the Django WSGI application entry point. Something like:

如果您无权访问任何Apache配置,如果需要,可以使用围绕Django WSGI应用程序入口点的WSGI包装器来完成。就像是:

import django.core.handlers.wsgi
_application = django.core.handlers.wsgi.WSGIHandler()

def application(environ, start_response):
  if environ['HTTP_HOST'] != 'www.example.com':
    start_response('301 Redirect', [('Location', 'http://www.example.com/'),])
    return []
  return _application(environ, start_response)

Fixing this up to include the URL within the site and dealing with https is left as an exercise for the reader. :-)

修复此问题以在网站中包含URL并处理https是留给读者的练习。 :-)

#2


15  

The PREPEND_WWW setting does just that.

PREPEND_WWW设置就是这样做的。

#3


3  

There is a lightweight way to do that involving VirtualHosts and mod_alias Redirect directive. You can define two VirtualHosts, one holding the redirect and another holding the site configuration:

有一种轻量级方法可以实现VirtualHosts和mod_alias Redirect指令。您可以定义两个VirtualHost,一个包含重定向,另一个包含站点配置:

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / http://www.example.com/
</VirtualHost>

<VirtualHost *:80>
    ServerName www.example.com
    # real site configuration
</VirtualHost>

And that will do the job.

这将完成这项工作。

#4


0  

A full thread about the issue exists here http://forum.webfaction.com/viewtopic.php?id=1516

这里存在关于该问题的完整主题http://forum.webfaction.com/viewtopic.php?id=1516

#5


0  

This also can be done with a middleware.

这也可以用中间件完成。

Some examples:

一些例子:

This is a better version of snippet-510:

这是一个更好的snippet-510版本:

class UrlRedirectMiddleware(object):
    """
    This middleware lets you match a specific url and redirect the request to a
    new url. You keep a tuple of (regex pattern, redirect) tuples on your site
    settings, example:

    URL_REDIRECTS = (
        (r'(https?)://(www\.)?sample\.com/(.*)$', r'\1://example.com/\3'),
    )
    """
    def process_request(self, request):
        full_url = request.build_absolute_uri()
        for url_pattern, redirect in settings.URL_REDIRECTS:
            match = re.match(url_pattern, full_url)
            if match:
                return HttpResponsePermanentRedirect(match.expand(redirect))

#6


0  

I've tried Graham's solution but can't get it to work (even if the simplest case of http (not https) without any path. I'm not experienced with wsgi as you can probably guess and all help is deeply appreciated.

我已经尝试了格雷厄姆的解决方案,但无法让它工作(即使最简单的情况是http(而不是https)没有任何路径。我没有经验wsgi,因为你可能猜到并且所有的帮助都深表赞赏。

Here's my attempt (redirecting from www.olddomain.com to www.newdomain.com). When I try to deploy it, trying to reach www.olddomain.com results in a error ("Can't reach this page"):

这是我的尝试(从www.olddomain.com重定向到www.newdomain.com)。当我尝试部署它时,尝试访问www.olddomain.com会导致错误(“无法访问此页面”):

from django.core.wsgi import get_wsgi_application

_application = get_wsgi_application()

def application(environ, start_response):
  if environ['HTTP_HOST'][:21] == 'www.olddomain.com':
    start_response('301 Redirect', [('Location', 'http://www.newdomain.com/'),])
  return []

  return _application(environ, start_response)

Thank you for your help

感谢您的帮助