Neil Ang


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 to On each page of the site I include a link to switch between the two sites. Example. If the user is viewing 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} !^
RewriteCond %{HTTP_COOKIE} !^.*no_iphone=yes.*$ [NC]
RewriteRule ^/(.*)$$1 [R,L]

# User requested normal site (sets cookie)
RewriteCond %{REQUEST_URI} ^/noiphone/.*$
RewriteRule ^/noiphone/(.*)$$1 [R,L,]

# User requested iphone site (removes cookie)
RewriteCond %{REQUEST_URI} ^/iphone/.*$
RewriteRule ^/iphone/(.*)$$1 [R,L,]

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.