Mobile Site Recognition Via htaccess

Using JavaScript to detect a browser type and redirect iPhones, iPad and other mobile devices is not very difficult to do.  However, it means that the page load has already happened as the JavaScript must be invoked before it can redirect the browser to the alternative page.

If you’re using Apache, you can redirect via htaccess.  This will let Apache redirect the browser before there are any assets downloaded.

This example is from, and includes a call to cookie the user so that you may code your pages to keep the user on the mobile site unless they choose to view the desktop version.

RewriteEngine On

# Check if this is the noredirect query string
RewriteCond %{QUERY_STRING} (^|&)noredirect=true(&|$)
# Set a cookie, and skip the next rule
RewriteRule ^ - [CO=mredir:0:%{HTTP_HOST},S]

# Check if this looks like a mobile device
# (You could add another [OR] to the second one and add in what you
#  had to check, but I believe most mobile devices should send at
#  least one of these headers)
RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
RewriteCond %{HTTP:Profile}       !^$
# Check if we're not already on the mobile site
RewriteCond %{HTTP_HOST}          !^m\.
# Check to make sure we haven't set the cookie before
RewriteCond %{HTTP:Cookie}        !\smredir=0(;|$)
# Now redirect to the mobile site
RewriteRule ^{REQUEST_URI} [R,L]

Leave a Reply

Your email address will not be published. Required fields are marked *