Redirect Entire Domain with Flask

My blog used to be served from I recently decided to serve it from my “root” subdomain, but I wanted to keep all the old links working. This means that should redirect to and that every URL should redirect to its appropriate counterpart under the new domain - should point to

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

from flask import Flask, redirect

app = Flask(__name__)
new_url = ''

def root():
    return redirect(new_url, code=302)

def anypage(page):
    return redirect('{new_url}/{page}'.format(page=page, new_url=new_url), 

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:

if __name__ == '__main__':'', port=5000)

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

Similar Posts