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]

3 thoughts on “Mobile Site Recognition Via htaccess

  • May 1, 2012 at 5:35 AM

    If you want to have a more sophisticated tool try to use Apache Mobile filter is easy to install, and is usable wit mod_rewrite.

    • May 2, 2012 at 7:16 AM

      Thanks — how is it better than simply adding an htaccess rule like the one posted above?

    • May 12, 2012 at 3:04 PM

      Idel, I guess you’re just interested in posting a link, but not really explaining the sophistication you speak of here.


Leave a Reply

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