Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

Using nginx, how do you serve different static files for different user agents? For example, if the current user is using an iPhone, they should be served mobile_index.html, whereas all other user agents should be served browser_index.html.

Found solution:

server {
  listen 80;
  root /var/www;

  set $mobile_request '0';
  if ($http_user_agent ~ 'iPhone') {
    set $mobile_request '1';
  }

  location =/ {
    if ($mobile_request = '1') {
      rewrite ^ /mobile_index.html;
    }
    if ($mobile_request = '0') {
      rewrite ^ /browser_index.html;
    }
  }
}
share|improve this question
    
why don´t redirect the mobile users to a mobile site? like m.mysite.com ??? –  Marcelo Bittencourt Oct 26 '11 at 20:08
    
because that's not what I want to do? –  summatix Oct 26 '11 at 20:10

1 Answer 1

up vote 5 down vote accepted

If you have a new enough version of nginx (0.9.6+), you could accomplish this with a map:

map $http_user_agent $myindex {
  default /browser_index.html;
  ~iPhone /mobile_index.html;
}

server {
  listen 80;
  root /var/www;

  location = / { rewrite ^ $myindex; }
}

If you don't need an internal redirect (which you probably don't if you're just serving static files for the indexes), you could add a 'break' flag to the rewrite and avoid the internal redirect.

EDIT: If you're using an older version, you could do something like this:

server {
  listen 80;
  root /var/www;

  location = / {
    set $myindex /browser_index.html;
    if ($http_user_agent ~ iPhone) {
      set $myindex /mobile_index.html;
    }
    rewrite ^ $myindex;
  }
}

again, using the break flag if you don't need the internal redirect.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.