Skip to content

Instantly share code, notes, and snippets.

@phillipadsmith
Created November 22, 2011 21:12
Show Gist options
  • Save phillipadsmith/1386982 to your computer and use it in GitHub Desktop.
Save phillipadsmith/1386982 to your computer and use it in GitHub Desktop.
Mobile site redirection using mod_rewrite
RewriteEngine On
# If the user is asking for the fullsite, set a cookie, remove the query, and stop.
RewriteCond %{QUERY_STRING} ^fullsite$
RewriteRule ^/?(.*)$ http://domain.com/$1? [L,CO=fullsite:yes:.domain.com]
# If the user is asking for the mobilesite, set a cookie, remove the query, redirect and stop.
RewriteCond %{QUERY_STRING} ^mobilesite$
RewriteRule ^/?(.*)$ http://m.domain.com/$1? [L,CO=fullsite:no:.domain.com]
# If the visit is from a mobile user agent, and there's no fullsite cookie, redirect and stop
# if the browser accepts these mime-types, it's definitely mobile, or pretending to be
RewriteCond %{HTTP_ACCEPT} "text\/vnd\.wap\.wml|application\/vnd\.wap\.xhtml\+xml" [NC,OR]
# a bunch of user agent tests
RewriteCond %{HTTP_USER_AGENT} "sony|symbian|nokia|samsung|mobile|windows ce|epoc" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "mini|nitro|j2me|midp-|cldc-|netfront|mot|up\.browser|up\.link|audiovox"[NC,OR]
RewriteCond %{HTTP_USER_AGENT} "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]
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
# Note: I've updated the conditions above to skip iPads. However,
# mobile safari still reports itself as 'mobile' and thus needs an explicit opt-out
RewriteCond %{HTTP_USER_AGENT} !iPad [NC]
RewriteCond %{HTTP_COOKIE} !^.*fullsite=yes.*$ [NC]
RewriteRule ^/?(.*)$ http://m.domain.com/$1 [L,R=302]
@chansdad
Copy link

This is great , close to what I was looking. Thanks for sharing.
How can we update this so that instead of %{QUERY_STRING} , it works with %{HTTP_HOST}. I am looking to direct a subdomain to either a full site or a mobile site full site. Full site is at a differnt url and mobile site is at a different url .
ex mysite.example.com/regularsite - regular site for desktops and ipads
mysite.example.com/mobilesite - mobile site for mobile devices
so when a user types in mysite.example.com in the browser ( desktop or mobile device ) is directed to the correct site.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment