网站搜索

根据使用的浏览器(Chrome、Firefox 或 IE)重定向网站请求


正如我们在上一篇文章(如何使用 mod_rewrite 执行内部重定向)中所承诺的那样,在这篇文章中,我们将解释如何根据用户的浏览器标准使用 Apache mod_rewrite 重定向请求来显示自定义网站内容。

理论上,所有现代浏览器都应该平等地解释内容。然而,有些应用程序比其他应用程序更快地实现最新功能。为了拥有一个功能齐全的网站,在使用某种浏览器查看时不会中断。不幸的是,这将需要重定向到不同的目录或页面。

建议阅读: 提升 Apache Web 服务器性能的 5 个技巧

以下重写规则会将 howtoing.html 的请求重定向到 howtoing-chrome.htmlhowtoing-firefox.htmlhowtoing -ie.html 取决于所使用的浏览器(Google Chrome、Mozilla Firefox 或 Internet Explorer)。

为此,HTTP_USER_AGENT 环境变量用于根据用户代理字符串识别浏览器。这里我们引入了 RewriteCond 指令,它允许我们指定发生重定向必须满足的条件。

RewriteCond "%{HTTP_USER_AGENT}"  ".*Firefox.*"
RewriteRule "^/tecmint\.html$"     	"/tecmint-firefox.html" [R,L]
RewriteCond "%{HTTP_USER_AGENT}"  ".*Chrome.*"
RewriteRule "^/tecmint\.html$"     	"/tecmint-chrome.html" [R,L]
RewriteCond "%{HTTP_USER_AGENT}"  ".*Trident.*"
RewriteRule "^/tecmint\.html$"     	"/tecmint-ie.html" [R,L]

请注意,目标页面 howtoing.html 不一定必须存在。首先,让我们使用以下内容创建 howtoing-firefox.htmlhowtoing-chrome.htmlhowtoing-ie.html

howtoing-firefox.html:
<!DOCTYPE html>
<html>
  <head>
	<meta charset="utf-8">
	<title></title>
  </head>
  <body>
	<h3>Welcome to Tecmint on Firefox!</h3>
  </body>
</html>
howtoing-chrome.html:
<!DOCTYPE html>
<html>
  <head>
	<meta charset="utf-8">
	<title></title>
  </head>
  <body>
	<h3>Welcome to Tecmint on Chrome!</h3>
  </body>
</html>
howtoing-ie.html:
<!DOCTYPE html>
<html>
  <head>
	<meta charset="utf-8">
	<title></title>
  </head>
  <body>
	<h3>Welcome to Tecmint on Internet Explorer!</h3>
  </body>
</html>

我们将看到使用不同浏览器浏览 howtoing.html 的结果:

正如您所看到的,对 howtoing.html 的请求根据所使用的浏览器进行了相应的重定向。

在本文中,我们讨论了如何根据用户的浏览器进行重定向请求。最后,我强烈建议您查看 mod_rewrite 备忘单,并在 Apache 文档中为重定向和重新映射指南添加书签以供将来参考。

与往常一样,如果您对本文有任何疑问或反馈,请随时使用下面的评论表。我们期待您的回音!