apache中基于user-agent的rewrite实例
最近在给一个网站增加手机版本访问,碰到个问题,如何区分客户端是电脑还是手机,查询资料有说通过判断request的User-Agent参数,进而产生不同的行为来,觉得可行,记录下资料。
1. 根据不同的 User-Agent 来给出 response出不同的内容出来,比较高级的让我觉得高级的是,这个通常应该是在代码层来完成的,现在可以通过修改Apache的配置,启用 mod_rewrite 来简单实现:
———–
Browser Dependent Content
Description:
At least for important top-level pages it is sometimes necessary to provide the optimum of browser dependent content, i.e. one has to provide a maximum version for the latest Netscape variants, a minimum version for the Lynx browsers and a average feature version for all others.
Solution: ….
We cannot use content negotiation because the browsers do not provide their type in that form. Instead we have to act on the HTTP header "User-Agent". The following condig does the following: If the HTTP header "User-Agent" begins with "Mozilla/3", the page foo.html is rewritten to foo.NS.html and and the rewriting stops. If the browser is "Lynx" or "Mozilla" of version 1 or 2 the URL becomes foo.20.html. All other browsers receive page foo.32.html. This is done by the following ruleset:
RewriteCond %{HTTP_USER_AGENT} ^Mozilla/3.*
RewriteRule ^foo\.html$ foo.NS.html [L]
RewriteCond %{HTTP_USER_AGENT} ^Lynx/.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^Mozilla/[12].*
RewriteRule ^foo\.html$ foo.20.html [L]
RewriteRule ^foo\.html$ foo.32.html [L]
———–
2. 根据User-Agent的不同,动态的修改response出去的Content-Type,这个尤其就更可贵了,不然如果要修改一个 .mp3的content-type为“video”则需要处理程序读出.mp3的内容,然后在stream被output之前设置一下content-type, 而如今通过apache可以在mod_rewrite里轻松实现:
———–
RewriteCond ${lowercase:%{HTTP_USER_AGENT}} ^dopod-s500
RewriteRule ^(.+\.png) – [T=video/png]
———–
如果将request的User-Agent全部小写后,里面是以dopod-s500开头的话,这样的ua请求.png的文件的时候,其返回的content-type修改为 video/png .
转载自 <a href="http://www.yanghengfei.com/archives/462/" title="apache中基于User-Agent的Rewrite实例" rel="bookmark">apache中基于User-Agent的Rewrite实例 | 星外飞客 </a>
我简单说几句