How do I redirect all requests with URLs beginning with "www" to a naked domain? How do I redirect all requests with URLs beginning with "www" to a naked domain? flask flask

How do I redirect all requests with URLs beginning with "www" to a naked domain?


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

Alternatively, you could register a before_request function:

from urlparse import urlparse, urlunparse@app.before_requestdef 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 will redirect all www requests to non-www using a "HTTP 301 Moved Permanently" response.


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

You may want to check http://werkzeug.pocoo.org/docs/routing/#custom-converters or http://werkzeug.pocoo.org/docs/routing/#host-matching