With a few mobile sites under my belt over the past couple years, the mobile development process has become easier. Naturally, with each new site, I try to improve the process just a little bit over the last development project.

This time around, I started to ponder the method used to detect mobile devices and redirect them to the mobile site.

For many, this method involves USER_AGENT detection in their scripting language, then a simple redirect to the mobile site.

For others, a web service is used to detect the user agent.

I'm the kind of guy that likes to squeeze every bit of performance juice possible out of any given task. So, in this case, sending a request to a page, then having that page redirect to another page just didn't seem optimal.

Where do requests go first? The web server, of course. So why can't we take care of all mobile redirection at the web server level. I'm sure many people are thinking, at this point, "duh, just use a mod_rewrite condition to check the USER_AGENT string". That works, no doubt.

But, what about storing the user's preference for desktop or mobile site in a cookie, and directing the user to the appropriate site based on that preference? It has to be done in the scripting language, right? I used to think the same thing about 3 hours ago!

Check out these two virtual host stanza's:

<VirtualHost *:80>
  ServerName m.yoursite.com
  DocumentRoot /var/www/html/yoursite_com/mobile
 
    RewriteEngine On
    RewriteCond %{QUERY_STRING}        mobile=true
    RewriteRule ^(.*) - [co=mobile:INVALID:.yoursite.com:-1] 
 </VirtualHost>

<VirtualHost *:80>
  ServerName www.yoursite.com
  DocumentRoot /var/www/html/yoursite_com

  RewriteEngine On

    RewriteCond %{HTTP_USER_AGENT} "android|blackberry|googlebot-mobile|iemobile|iphone|ipod|opera mobile|palmos|webos" [NC]
    RewriteCond %{QUERY_STRING}        !mobile=false
    RewriteCond %{HTTP_COOKIE}        !^.*mobile.*$ [NC]
    RewriteRule ^/(.*) http://m.yoursite.ccom/ [L,R=302]

    RewriteCond %{QUERY_STRING}        mobile=false
    RewriteRule ^(.*) - [co=mobile:false:.yoursite.com:2592000:/]

  </VirtualHost>

 

There you have it. The entire load of detection and storing the users preference can be done entirely in Apache, by leveraging mod_rewrites ability to set and retrieve cookies.

Tags:

Leave a Reply

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