How do I redirect domain.com to WWW.domain.com under Django?

南楼画角 提交于 2019-11-28 06:37:14

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.

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.

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:

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. :-)

The PREPEND_WWW setting does just that.

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:

<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.

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

This also can be done with a middleware.

Some examples:

This is a better version of 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))

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.

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"):

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!