beachcoder.co.uk

26Jun/11Off

Mobile redirects via .htaccess

Rather than have the overhead of your web app checking for mobile devices (or, God forbid, Javascript) .htaccess can provide a much neater solution. It's a single file, completely independent from the rest of your application, and runs on most webservers including IIS (with the right plugins).

This is a script I use that redirects mobile users from www.example.com over to m.example.com. It includes checks for iPads and Macs which would otherwise trigger as a mobile device, when in fact they should be served the full site by default.

There's a link on m.example.com back to the full site if the user wants it; this just needs a single GET variable like so: http://www.example.com?nomobile
That will set a cookie on the mobile device allowing it to skip the mobile checks and redirect.

RewriteEngine On
RewriteBase /
 
# Has not requested the full site
RewriteCond %{QUERY_STRING} !nomobile$ [NC,OR]
 
# Thre’s no ‘nomobile’ cookie
RewriteCond %{HTTP_COOKIE} !nomobile=1 [NC,OR]
 
RewriteCond %{HTTP_ACCEPT} "text\/vnd\.wap\.wml|application\/vnd\.wap\.xhtml\+xml" [NC,OR]
 
# Mobile user agent tests
RewriteCond %{HTTP_USER_AGENT} "sony|symbian|nokia|samsung|mobile|windows ce|epoc|opera" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "mini|nitro|j2me|midp-|cldc-|netfront|mot|up\.browser|up\.link|audiovox"[NC,OR]
RewriteCond %{HTTP_USER_AGENT} "blackberry|ericsson,|panasonic|philips|sanyo|sharp|sie-"[NC,OR]
RewriteCond %{HTTP_USER_AGENT} "portalmmm|blazer|avantgo|danger|palm|series60|palmsource|pocketpc"[NC,OR]
RewriteCond %{HTTP_USER_AGENT} "smartphone|rover|ipaq|au-mic,|alcatel|ericy|vodafone\/|wap1\.|wap2\.|iPhone|android"[NC,OR]
 
# Not Mac/iPad
RewriteCond %{HTTP_USER_AGENT} !macintosh [NC,OR]
RewriteCond %{HTTP_USER_AGENT} !ipad [NC]
 
# Redirect to mobile site
RewriteRule .* http://m.example.com/ [r=302]

# Has requested full site
RewriteCond %{HTTP_COOKIE} "nomobile=1" [NC,OR]
RewriteCond %{QUERY_STRING} nomobile [NC]
 
# Set ‘nomobile’ cookie
RewriteRule .* - [co=nomobile:1:.example.com:7200:/]