爱简单吧

分享简单,爱生活,爱简单

一个好用的301 转向代码

对有多个域名的或换域名的网站很有用,python 框架里较底层的转向,对遵循WSGI规范的环境均有效。





域名301转向keakon YUI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from urlparse import urlunsplit

application = Application()

def redirect_to_major_domain(wsgi_app, major_domain, ignore_scheme=False):
 def redirect_if_needed(env, start_response):
     if env['HTTP_HOST'] != major_domain and env['REMOTE_ADDR'][:2] != '0.' and (ignore_scheme or env['wsgi.url_scheme'] == 'http'):
         url = urlunsplit(['http', major_domain, env['PATH_INFO'], env['QUERY_STRING'], ''])
         start_response('301 Moved Permanently', [('Location', url)])
         return []
     else:
         return wsgi_app(env, start_response)
 return redirect_if_needed

application = redirect_to_major_domain(application, MAJOR_DOMAIN)

但有个情况不能使用,在vps 上用nginx 反向代理到一个sinaapp.com 的二级域名,BAE 的没试过。

 

Share

 

Comments