06 januari 2012

Serving mobile users with nginx

Using nginx, and don't want to use PHP to redirect mobile users to your mobile-optimized site? Well, it's perfectly possible to detect and redirect them with some nginx configuration file magic.

This is the setup I came up with:

nginx configuration file
location / {
    set $mobile_request '1';
    if ($http_user_agent ~* "(windows|linux|os\s+[x9]|solaris|bsd)"){
        set $mobile_request '';
    if ($http_user_agent ~* "(spider|crawl|slurp|bot)"){
        set $mobile_request '';

    if ($http_user_agent ~* "(acer\ s100|android|archos5|blackberry9500|blackberry9530|blackberry9550|blackberry\ 9800|cupcake|docomo\ ht\-03a|dream|htc\ hero|htc\ magic|htc_dream|htc_magic|incognito|ipad|iphone|ipod|kindle|lg\-gw620|liquid\ build|maemo|mot\-mb200|mot\-mb300|nexus\ one|nokia|opera\ mini|samsung\-s8000|series60.*webkit|series60/5\.0|sonyericssone10|sonyericssonu20|sonyericssonx10|t\-mobile\ mytouch\ 3g|t\-mobile\ opal|tattoo|webmate|webos)") {
        set $mobile_request '1';
    if ($arg_mobile ~ 'false') {
        set $mobile_request '';
    if ($mobile_request = '1') {
        rewrite ^/$ http://m.an3s.com/ redirect;

Explanation of steps:
  1. Set the default to the mobile-optimized version
  2. Filter desktops
  3. Filter crawlers like Googlebot
  4. If somehow a mobile browser slipped through (because it was detected as desktop, it reported for example to run Linux, like Android does), mark it again as mobile
  5. Filter requests that have ?mobile=false
  6. Point anything left to the mobile-version of the site, using an 302 Temporary redirect header

If your user decides it wants to use the non-mobile version, you can simply point him to the ?mobile=false link.

Surf with your mobile browser to https://www.andrieslouw.nl/, it should redirect you to https://m.an3s.com/. You can use the third link on that page to go to the non-mobile version, or simply use https://www.andrieslouw.nl/?mobile=false.

This version lacks an option to remember the setting (mobile/non-mobile) the user prefers. You could make such thing yourself, by setting an cookie and reading it in the configuration file.

Any additions are welcome, you can post them in the comments!

1 opmerking:

  1. You can always use a cookie say site_pref and use $cookie_site_pref to check for values instead of arg ! This way caching will also work properly.