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

I have a Python Flask application running on Heroku (Cedar stack) with two user domains (one with one and without the www subdomain). I would like to redirect all incoming requests to www. version of the requested resource (reverse this question ). I think I need some WSGI middleware for this, but I can't find a good example.

How to do it?

+8
python flask heroku
source share
4 answers

A simpler solution than creating a standalone Heroku application would be the before_request function.

 from urlparse 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 redirects all non-www requests to www using the HTTP 301 Moved Permanentently response.

+12
source share

According to Heroku docs, you have the right idea about using the www subdomain (e.g. www.foo.com) and the apex domain (e.g. foo.com). Their suggestion to solve this problem is to use a DNS server redirection:

Quote:

Subdomain Redirection

Forwarding a subdomain leads to 301 permanent redirection to the specified subdomain for all requests to the apex domain, so all current and future requests are correctly routed, and the full name of the www-site is displayed in the user location field.

Almost all DNS providers offer domain forwarding services - sometimes also called domain forwarding. DNSimple provides a convenient redirect URL, visible here, redirecting from the top of the heroku-sslendpoint.com domain to the subdomain www.heroku-sslendpoint.com.

Source: http://devcenter.heroku.com/articles/avoiding-apex-domains-dns-arecords#subdomain_redirection

Hope this helps!

+3
source share

One possible approach would be to add a function to listen for request_started and do the appropriate redirection.

This signal is sent before the request is processed, but when the request context was set. Since the request context is already connected, the subscriber can access the request with a standard global proxy, for example, a request.

+1
source share

What I ended up was creating a second Heroku application, assigning it a non-www hostname and using the catch All Flask route to redirect to the www version, keeping the path intact.

0
source share

All Articles