Neil Ang

Developer

A stunning likeness of Neil Ang
Hello world

Redirect to iPhone site with htaccess

Posted on

This is my implementation of how to redirect to an iPhone optimised website using Apache rewrite rules and cookies. Although this redirect can be achieved easily through server-side scripting, websites that implement heavy page caching need to redirect at the request level.

The interaction: If the user is using an iPhone to view the site, I wanted to automatically redirect them to the iphone site, however I also wanted to allow the user to switch between the two versions of the website freely - and to remember their preference for which version of the site they wanted to view when they returned. I also didn't want to embed absolute URLs into links or append parameters to the end of urls.

So these are the rules I came up with to redirect an iphone visiting www.example.com to i.example.com. On each page of the site I include a link to switch between the two sites. Example. If the user is viewing i.example.com/about.html there would be a server relative link to "/noiphone/about.html" and on the normal site there would be a link to "/iphone/about.html" etc.

# Always redirect to the iphone site (unless there is a cookie)
RewriteCond %{HTTP_USER_AGENT} iPhone
RewriteCond %{HTTP_HOST} !^i.example.com
RewriteCond %{HTTP_COOKIE} !^.*no_iphone=yes.*$ [NC]
RewriteRule ^/(.*)$ http://i.example.com/$1 [R,L]

# User requested normal site (sets cookie)
RewriteCond %{REQUEST_URI} ^/noiphone/.*$
RewriteRule ^/noiphone/(.*)$ http://www.example.com/$1 [R,L,CO=no_iphone:yes:.example.com:10080]

# User requested iphone site (removes cookie)
RewriteCond %{REQUEST_URI} ^/iphone/.*$
RewriteRule ^/iphone/(.*)$ http://i.example.com/$1 [R,L,CO=no_iphone:0:.example.com:-1]

You may notice that the cookie expire time to remember their preference is set to 10080 minutes (1 week), you may want to adjust this if you don't want their preference to expire.