开发者

django flatpage redirects

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 fl开发者_如何学JAVAatpages.

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

Anyone know how I should go about doing this?


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


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
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜