.htaccess Redirecting to a specific browser-based web page

I want to redirect visitors to my specific page based on which browser they use.

For example: all visitors first visit http://www.example.com/xy/abc.html .

If the visitor uses firefox, he should be redirected to http://www.example.com/xy/firefox.html

If the visitor uses chrome, he should be redirected to http://www.example.com/xy/chrome.html

I want to handle this for opera, chrome, firefox, IE, Safari browser and with default redirection for unidentified browser.

Any help with the code? I tried searching, and all I found was the only redirect code for the entire browser, and not for the specific one.

Your help is appreciated. Thanks.

+6
source share
1 answer

You can use the mod_rewrite RewriteCond directive to test against the reported user agent name. In the .htaccess file placed in your xy directory, it will look like this:

RewriteCond %{HTTP_USER_AGENT} Opera RewriteRule ^abc.html$ http://example.com/xy/opera.html [R=301] 

This will result in a constant redirection of browsers, where Opera is in the line of its user agent, in opera.html. You can find a decent list of how user agents identify themselves at useragentstring.com . You'll notice that many user agent strings actually start with โ€œMozillaโ€ (due to some evil historical reasons), but just checking if the string will contain the browser name (IE โ€œMSIEโ€).

The problem is that the HTTP_USER_AGENT line HTTP_USER_AGENT reported by the browser, and the browser can pretty much report everything they want. Opera even has a built-in option to make it masquerade itself as IE or FF. Typically, there is a good chance that browser sniffing based on the user agent string will eventually be skipped and then the user will be annoyed. I highly recommend that you leave the user in some way to override automatic redirection.


So something like this might work as a first approach:

 RewriteEngine on RewriteCond %{HTTP_USER_AGENT} Opera RewriteRule ^abcd.html$ opera.html [NC,L] RewriteCond %{HTTP_USER_AGENT} MSIE RewriteRule ^abcd.html$ ie.html [NC,L] RewriteCond %{HTTP_USER_AGENT} Chrome RewriteRule ^abcd.html$ chrome.html [NC,L] RewriteCond %{HTTP_USER_AGENT} Safari RewriteRule ^abcd.html$ safari.html [NC,L] RewriteCond %{HTTP_USER_AGENT} Firefox RewriteRule ^abcd.html$ firefox.html [NC,L] RewriteRule ^abcd.html$ default.html [L] 

The L flag ensures that this rule is the last to be executed in this passage, therefore, if the browser reports itself with a string containing Firefox, Safari, MSIE and Opera, then the first rule matches (in this case Opera) will determine the landing page. This version performs soft redirection (browser address bar does not change). If you need a hard redirect R = 301, make sure you provide the entire landing page URL, that is, RewriteRule ^abcd.html$ http://example.com/xy/opera.html [NC,L,R=301]

+11
source

All Articles