Monday, October 22, 2012

Redirect all request to specific site to new location with appengine

Let say you have web site with complex structure, what stop work for some reason, and you want redirect all request for you site to new location, instead of showing 404 error.

Example:

http://www.oldsite.com/about.html -> http://www.newsite.com/temporarily.html 
http://www.oldsite.com/product.php?id=12 -> http://www.newsite.com/temporarily.html 
http://oldsite.com/product.php?id=12 -> http://www.newsite.com/temporarily.html 
http://oldsite.com/group.php?id=12 -> http://www.newsite.com/temporarily.html

Make what with Google AppEngine. It's free and simple.

  1. You need to create an application on Google Appengine Platform
  2. Now you have http://YOU-APP-ID.appspot.com page where you place handler for you request
  3. For accessing to you app by you custom domain name (www.oldsite.com) instead YOU-APP-ID.appspot.com you need prove you right for what name and add what name in Domain Setup part of YOU-APP-ID application settings page.
  4. Add CNAME record www in DNS settings for oldsite.com and point it to "ghs.googlehosted.com."
  5. Now you need to create and deploy app for handling requests:
    1. Download actual version o Google App Engine SDK for Python
    2. Install SDK and create new app with YOU-APP-ID as application ID
    3. Edit file app.yaml:

    4. application: YOU-APP-ID
      version: 1
      runtime: python
      api_version: 1
      
      handlers:
      - url: .*
        script: main.py
    5. Add main.py:
      from google.appengine.ext import webapp
      from google.appengine.ext.webapp import util
      
      class Redirect (webapp.RequestHandler):
          def get(self):
              self.redirect('http://www.newsite.com/temporarily.html', permanent=True)
                  
      def main():
          application = webapp.WSGIApplication([
              ('/.*', Redirect)
              ],debug=True)
          util.run_wsgi_app(application)
      if __name__ == '__main__':
          main()
      
    6. Deploy app to Google
  6. Now you app redirect all request from www.oldsite.com/anything  to http://www.newsite.com/temporarily.html.
  7. In addition we need to redirect all non www request to request with www, sadly you can not do that redirect only by dns server, you need some magic on http server. In Lighttpd i solve what with adding in conf file:
    $HTTP["host"] =~ "^oldsite\.com$" { url.redirect = ( "^/(.*)" => "http://www.oldsite.com/$1" ) }

Done!

No comments:

Post a Comment