How Do I Redirect All Requests With Urls Beginning With "www" To A Naked Domain?
I have been successful in adding Heroku custom domains for my app. I'd like to know how to capture requests that begin with www and redirect them to the naked domain. For example,
Solution 1:
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_requestdefredirect_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.
Solution 2:
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
Post a Comment for "How Do I Redirect All Requests With Urls Beginning With "www" To A Naked Domain?"