views:

311

answers:

3

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

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

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

I'm guessing something in middleware or apache conf?

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

+1  A: 

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

damirault
That thread refers to a control panel I do not have. It gives a link to the Django docs for PREPEND_WWW, this is the behavior I need, but I'd prefer a 301 redirect.
Jake
+4  A: 

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

Graham Dumpleton
That is a pretty slick little WSGI snippet. Definitely more elegant than the thing I linked.
jathanism
I have cheated a bit though. I have assumed 'http' only and haven't bothered with reconstructing the full URL and left that up to reader. Wanted to show the concept more than anything. The Django middleware is more correct. Overall though, mod_rewrite should simply be used.
Graham Dumpleton
Using Apache/Lighttpd/nginx configuration is more efficient than using django for this work.
jujule
Thanks everyone! Just what I was looking for.
Jake
+3  A: 

The PREPEND_WWW setting does just that.

Luper Rouch