Table of Content

.htaccess iPhone Detection



.htaccess file can be used for iPhone Detection. In order to make better user experience to all the website visitors it is very important to redirect users to mobile compatible website whenever possible if your website is not responsive website.

iPhone Detection using .htaccess file

In case of the mobile user if you want to detect the Apple’s iPhone .htaccess file will surely help you to do this. We can detect the iPhone user and redirect him/her to iPhone specific website.

How iPhone Visitor is detected ?

Consider following code snippet –

echo $_SERVER['HTTP_USER_AGENT'];
$browser = get_browser();
print_r($browser);

Above code is written in PHP which will return you the information of the user’s browser, operating system etc.

.htaccess iPhone Detection

.htaccess code examine the HTTP header “User-Agent” which all browser send. In case of iPhone, User-Agent header is similar to this –

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25

Way 1 : Redirect user to iPhone specific subdomain

RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} iPhone
RewriteRule .* http://iphone.site.com/ [R]

Above code snippet in .htaccess file will redirect iPhone user to iPhone specific website subdomain. In this case iPhone user will be redirected to below url –

http://iphone.site.com/

Way 2 : Redirect user to iPhone specific directory

RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} iPhone
RewriteCond %{REQUEST_URI} !^/iPhone-site/
RewriteRule .* /iPhone-site/ [R]

In the above case iPhone user will be redirected to directory site called /iPhone-site

Way 3 : Redirect iPhone user using JavaScript

<script type="text/javascript">
<!--
if ((navigator.userAgent.match(/iPhone/i))) {
   location.replace("http://iPhone.site.com/");
}
-->
</script>

We can achieve it using the JavaScript as well using way specified in above code snippet. Please find some more approaches of achieving it by following this discussion

Note and Summary

  1. Do not use JavaScript approach because user may turn JS on/off depending on his/her wish so try to put this code in .htaccess file.
  2. Simply in other way you can put link at the header or footer to switch to iPhone specific stie.