Another Apache config file for mobile device detection

Recently I posted an Apache configuration file that allows you to detect mobile devices and pass a query parameter to the back-end that informs your web application what type of device is accessing your website. This without the need for device detection in your back-end (e.g. Drupal).

The main goals for that script where:

  • 1 url for both the mobile and desktop site
  • Allow for caching within an web application framework or even more specific, allow Boost to be used.
  • Pass a "device" query parameter to the back-end framework to identify which device is accessing the site

I recently also made a second .htaccess with a slightly different goal:

  • Separate URL's for different device groups
  • Allow for caching within an web application framework or even more specific, allow Boost to be used.

This is the result:

 ### BOOST + Mobile Customization ###
 
# Put this in your .htaccess file (if you use Boost, put it before the Boost directives.)
 
  # By default we assume that the accessing device is a desktop browser
  RewriteRule .* - [E=device:www]
 
  # If the user agent matches our definition of high end (mh) or low end (ml) device we set tour device variable
  # overwrite the %{VAR:device} variable.
  # These user agent expression should be adjusted according to your requirements.
  RewriteCond %{HTTP_USER_AGENT} ^.*(iphone|android).*$ [NC]
  RewriteRule .* - [E=device:mh]
  RewriteCond %{HTTP_USER_AGENT} ^.*(nokia|BlackBerry).*$ [NC]
  RewriteRule .* - [E=device:ml]
  # above rules can be extended with multiple device categories
 
  # We allow users to override the device detection. 
  # (See next rules where a cookie will be set). 
  # Here we detect if a cookie is present and we use the cookie value.
  # If there is a cookie set, overwrite the %{VAR:device} variable with that value
  RewriteCond %{HTTP_COOKIE} ^.*device=(mh|ml|www)$
  RewriteRule .* - [E=device:%1]
 
  # We can provide device detection overwrite links by creating url's
  # that contain the device query parameter. 
  # If this is present we set the device parameter and set a cookie.
 RewriteCond %{QUERY_STRING} ^.*device=(mh|ml|www).*$
  RewriteRule .* - [E=device:%1,CO=device:%1:.boost.local:1000:/]
 
  # Do the necessary checks if the subdomain equals the device.
  # If so skip the Redirect rule, otherwise we have a redirection loop
  RewriteCond %{ENV:device} ^mh$
  RewriteCond %{HTTP_HOST}  ^mh\.boost\.local
  RewriteRule .* - [S=3]
 
  RewriteCond %{ENV:device} ^ml$
  RewriteCond %{HTTP_HOST}  ^ml\.boost\.local
  RewriteRule .* - [S=2]
 
  RewriteCond %{ENV:device} ^www$
  RewriteCond %{HTTP_HOST}  ^www\.boost\.local
  RewriteRule .* - [S=1]
 
  # Finally we redirect if needed to the right subdomain
  RewriteCond %{ENV:device} ^.*(mh|ml|www).*$
  RewriteRule ^(.*)$ http://%1.domain.com/$1 [L,R]

Feel free to experiment with this!