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

from flask import Flask, redirect


app = Flask(__name__)
new_url = 'http://amir.rachum.com'


@app.route('/')
def root():
    return redirect(new_url, code=302)


@app.route('/<path:page>')
def anypage(page):
    return redirect('{new_url}/{page}'.format(page=page, new_url=new_url), 
                    code=302)

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__':
    app.run(host='0.0.0.0', 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