Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I redirect to the www. version of my Flask site on Heroku?

I've got a Python Flask app running on Heroku (Cedar stack) with two custom domains (one with and one without the www subdomain). I'd like to redirect all incoming requests to the www. version of the resource requested (the inverse of this question). I think I need some WSGI middleware for this but I can't find a good example.

How do I do this?

like image 541
John Sheehan Avatar asked Mar 19 '12 06:03

John Sheehan


1 Answers

An easier solution than to create a separate Heroku app would be a before_request function.

from urllib.parse import urlparse, urlunparse

@app.before_request
def redirect_nonwww():
    """Redirect non-www requests to www."""
    urlparts = urlparse(request.url)
    if urlparts.netloc == 'example.com':
        urlparts_list = list(urlparts)
        urlparts_list[1] = 'www.example.com'
        return redirect(urlunparse(urlparts_list), code=301)

This will redirect all non-www requests to www using a "HTTP 301 Moved Permanently" response.

like image 171
Danilo Bargen Avatar answered Nov 01 '22 12:11

Danilo Bargen