views:

251

answers:

2

I want to make sure all of my flatpages have the "www" subdomain and redirect to it if they don't. I've looked at some middlewares that redirect to www, but 1. they usually redirect all urls to www and 2. the ones I've found don't work with flatpages.

I don't want all of my site urls to redirect to include the www subdomian, just the flatpages.

Anyone know how I should go about doing this?

Thanks

A: 

One option is to modify a middleware, so that it only redirects if response.status_code == 404. Put the middleware just before the flatpage middleware in settings.py. This would redirect

http://example.com/flatpage/ -> http://www.example.com/flatpage/

but also

http://example.com/invalidurl/ -> http://www.example.com/invalidurl/

before returning a 404 error.


Another option would be to write your own flatpage middleware based on the official one. You can see the code for the FlatpageFallbackMiddleware class on the django website.

In the try, except block, check to see if a flatpage exists. Then redirect if appropriate. If you don't redirect, return the flatpage.

...
try:
    fp = flatpage(request, request.path_info)

    # Code to redirect to www goes here

    return fp
except Http404:
...
Alasdair
A: 

In your urls.py file do something like this:

urlpatterns = patterns('',
    (r'^flat/(?P<static>.*)$', 'django.views.generic.simple.redirect_to', {'url': 'http://www.mysite.com/flat/%(static)s'}),
    # other stuff
)
-1: This creates an infinite redirect. `mysite.com/flat/page` -> `www.mysite.com/flat/page` -> `www.mysite.com/flat/page` -> ...
Alasdair