Reputation: 41
How can you configure an htaccess
file redirect android clients to one URL and iPhone clients to another?
Upvotes: 3
Views: 7155
Reputation: 47996
Sure you can! All you have to do is take a look at the user agent and perform a redirect if a condition is met.
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} "android" [NC]
RewriteRule ^(.*)$ /android/$1 [L,QSA]
RewriteCond %{HTTP_USER_AGENT} "iphone|ipod|ipad" [NC]
RewriteRule ^(.*)$ /ios/$1 [L,QSA]
Let me break down what's going on here. Firstly, we are making sure that the RewriteEngine
is turned on (v.important). The RewriteCond
lines are conditions that have to be met for the rule that comes after them to be enforced. The condition, in our case is the appearance of certain keywords in the user agent of the device making the request. The first condition matches the word "android" and the second one matches any of the strings "iphone","ipod","ipad". The text matching is done using regular expressions.
The lines after each RewriteCond
are the actual rules that do the URL rewriting (what appears to the end user as a redirection) according to their device. The rule says to take the entire request (again with regular expressions) and add to the beginning /android
or /ios
. The $1
that you see represents the actual request string that is being rewritten.
[NC]
means the match is case insensitive (no-case). IE Android == aNdroid
, IOS == iOS
, etc...[L]
means that the current rule is the last one and no other conditions or rules are executed.
If all you are only looking for is a distinction between android and ios devices you might be able to get away with a simple android
or iphone/ipad/ipod
. If you are wanting to detect specific devices you'll have to match it's user agent more specifically.Upvotes: 11