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

这一生的挚爱 提交于 2019-12-10 21:16:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!