[英]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. 我成功地为我的应用添加了Heroku自定义域名。 I'd like to know how to capture requests that begin with
www
and redirect them to the naked domain. 我想知道如何捕获以
www
开头的请求并将它们重定向到裸域。 For example, I have the following custom domains mapped to my Heroku app: 例如,我将以下自定义域映射到我的Heroku应用程序:
www.myapp.com
myapp.com
Requests for http://myapp.com
and http://www.myapp.com
are both successful, but the www
stays on. 对
http://myapp.com
和http://www.myapp.com
请求都是成功的,但www
仍然存在。
I want all requests for http://www.myapp.com
to be redirected to http://myapp.com
. 我希望将
http://www.myapp.com
所有请求重定向到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
. 这也适用于其他路径,例如
http://www.myapp.com/some/foo/bar/path
重定向到http://myapp.com/some/foo/bar/path
。 I want something like this: http://www.stef.io and see how the www.
我想要这样的东西: http : //www.stef.io并看看如何
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. 到目前为止,我在Google上找到的说明是关于编辑我的
.htaccess
文件,但是我正在使用Flask框架上的Python应用程序在Heroku上运行。
The recommended solution for this is DNS level redirection (see heroku help ). 建议的解决方案是DNS级别重定向(请参阅heroku帮助 )。
Alternatively, you could register a before_request
function: 或者,您可以注册
before_request
函数:
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. 这将使用“HTTP 301 Moved Permanently”响应将所有www请求重定向到非www。
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". 我不习惯Flask,但你可以设置一个匹配/^www./的路由,然后将其重定向到没有“www”的url。
You may want to check http://werkzeug.pocoo.org/docs/routing/#custom-converters or http://werkzeug.pocoo.org/docs/routing/#host-matching 您可以查看http://werkzeug.pocoo.org/docs/routing/#custom-converters或http://werkzeug.pocoo.org/docs/routing/#host-matching
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.