问题
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, I have the following custom domains mapped to my Heroku app:
www.myapp.com
myapp.com
Requests for http://myapp.com
and http://www.myapp.com
are both successful, but the www
stays on.
Objective
I want all requests for http://www.myapp.com
to be redirected to http://myapp.com
. This should also work for other paths, like 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 the www.
is gone from the address bar.
The instructions I've found on Google so far are about editing my .htaccess
file, but I'm running on Heroku with a Python app on the Flask framework.
回答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_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 will redirect all www requests to non-www using a "HTTP 301 Moved Permanently" response.
回答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
来源:https://stackoverflow.com/questions/9350141/how-do-i-redirect-all-requests-with-urls-beginning-with-www-to-a-naked-domain