views:

248

answers:

2

When a webpage has moved to a new location, how do I show the moved web page AND return a 301 permanent redirect HTTP response status code in Django?

+3  A: 

You can't.

301 is an HTTP return code that is directly acted upon by the browser. Many sites handle these two issues by first sending the user to a redirect-er page that tells the user about the change and then X seconds later sends them to the new page. But the redirect-er page must have a 200 code.

One small variant is to detect search engine spiders (by IP and/or user agent) and give them the 301. That way the search results point to your new page.

Peter Rowell
You actually can return an HTML page in a 301 or other redirect. It will be rendered by user-agents too old to understand the result - that is, HTTP/0.9 browsers, which pretty much don't exist any more.
bobince
I didn't know that! Of course, I don't find myself worrying about browsers that old, but still, it is interesting.
Peter Rowell
+6  A: 
   from django import http

   return http.HttpResponsePermanentRedirect('/yournewpage.html')

the browser will get the 301, and go to /yournewpage.html as expected. the other answer is technically correct, in that python is not handling the redirection per se, the browser is. this is what's happening under the hood:

Browser             Python         HTTP
   ------------------->            GET /youroldpage.html HTTP/1.1

   <-------------------            HTTP/1.1 301 Moved Permanently
                                   Location: /yournewpage.html
   ------------------->            GET /yournewpage.html HTTP/1.1
Owen