Redirect Entire Domain with Flask
My blog used to be served from blog.amir.rachum.com
. I recently decided to serve it from my “root” subdomain amir.rachum.com
, but I wanted to keep all the old links working. This means that blog.amir.rachum.com
should redirect to amir.rachum.com
and that every URL should redirect to its appropriate counterpart under the new domain - blog.amir.rachum.com/x/y/z
should point to amir.rachum.com/x/y/z
.
There’s no simple HTML trick for this (that I know). I’m usually a Django guy, but Django has too much overhead for this simple requirement (just creating a new Django project creates more files than I need lines of code). My brother suggested Flask, since it has a much smaller footprint (codewise).
Well, here it is (in all its glory):
Kudos for Flask for making it so simple to get right down to business. I had exactly zero experience working with Flask and was literally writing this code with one hand (the other one holding my baby daughter).
To test this code on my machine, I added the following snippet to the end of the file:
I also used this handy guide to deploy the Flask app to Webfaction. It only took a couple of minutes.
Discuss this post at Hacker News, /r/Python, or the comment section below.Follow me on Twitter and Facebook