如何重定向所有请求,URL以“www”开头到裸体域? [英] How do I redirect all requests with URLs beginning with "www" to a naked domain?

查看:178
本文介绍了如何重定向所有请求,URL以“www”开头到裸体域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功地为我的应用添加了Heroku自定义域。我想知道如何捕获以 www 开始的请求,并将其重定向到裸域。例如,我有以下自定义域映射到我的Heroku应用程序:

  www.myapp.com 
myapp。 com

请求 http://myapp.com http://www.myapp.com 都是成功的,但 www p>

目标



我希望所有请求 http://www.myapp.com 被重定向到 http://myapp.com 。这也适用于其他路径,例如 http://www.myapp.com/some/foo/bar/path 重定向到 http:/ /myapp.com/some/foo/bar/path 。我想要这样的: http://www.stef.io ,看看 www。已从地址栏中删除。



目前为止,Google发现的说明是关于编辑我的 .htaccess 文件,但是我在Flask框架上使用Python应用程序在Heroku上运行。

解决方案

推荐的解决方案是DNS级别重定向(请参阅 heroku帮助)。



或者,您可以注册一个 before_request 函数:

  from urlparse import urlparse,urlunparse 

@ app.before_request
def redirect_www():
重定向www请求到非www。
urlparts = urlparse(request.url)
如果urlparts.netloc =='www.stef.io':
urlparts_list =列表(urlpart
urlparts_list [1] ='stef.io'
return redirect(urlunparse(urlparts_list),code = 301)

这将使用HTTP 301 Moved Permanently响应将所有www请求重定向到非www。


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.

解决方案

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.

这篇关于如何重定向所有请求,URL以“www”开头到裸体域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆