How to redirect all requests with URLs starting with "www" to the bare domain?

I was able to add Heroku custom domains for my application. I would like to know how to grab requests starting with www and redirect them to a bare domain. For example, I have the following user domains mapped to my Heroku application:

 www.myapp.com myapp.com 

Requests for http://myapp.com and http://www.myapp.com succeeded, but www remains enabled.

purpose

I want all requests for http://www.myapp.com be redirected to http://myapp.com . This should also work for other paths, e.g. http://www.myapp.com/some/foo/bar/path redirects to http://myapp.com/some/foo/bar/path . I want something like this: http://www.stef.io and see how www. left the address bar.

The instructions I have found so far on Google are about editing my .htaccess file, but I am running a Python application on a flash framework on Heroku.

+3
redirect python flask dns heroku
source share
2 answers

The recommended solution for this is DNS level redirection (see heroku help ).

Alternatively, you can register the before_request function:

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

This redirects all www requests to non-www using the "HTTP 301 Moved Permanentently" response.

+7
source share

I'm not used to Flask, but you can configure a route that matches /^www./, and then redirect it to a url without "www".

You can check out http://werkzeug.pocoo.org/docs/routing/#custom-converters or http://werkzeug.pocoo.org/docs/routing/#host-matching

0
source share

All Articles