Home » Flask 技巧 » Flask中实现域名301重定向
  • 28
  • 08月

当然,这是一种非常不明智的做法,只是一种临时性的手段。301重定向应该由服务器层面的应用程序(比如NGINX,APACHE,IIS等)来完成。

代码示例如下:

def RedirectMiddleWare(request):
    url = None
    domain = 'www.digwtx.com'
    try:
        host, port = request.host.split(':')
        path = request.path
    except:
        host = request.host
        port = 80
        path = request.path

    if host != domain:
        print 'do 301'
        if port == 80:
            url = 'http://%s%s' % (domain, path)
        else:
            url = 'http://%s:%s%s' % (domain, port, path)
    return url