HOWTO: Redirect iPhone/iPod Users on Nginx

The blog is currently being ported from WordPress to over 12 years of static pages of content. If there's an article missing that you're hoping to see, please contact me and let me know and I'll prioritize getting it online.

January 20, 2010

I learned a little something about nginx, a small footprint web server ideal for serving mobile sites, or sites where you don’t want the heavy overhead of Apache.

While I was serving in a DevOps role at Armor Games, I needed to redirect iPhone/iPod users to a different URL for a promotion. Since nginx at the time didn’t have the ability to utilize mod_rewrite rules, I had to learn how to enable redirection at the server level.

Since nginx was already compiled with redirection support, I had to locate the correct configuration file and add a few lines of code, and away it went.

First, I reviewed /etc/nginx/ and opened the site configuration file within the sites-enabled/ path. For this example, let’s say the site was

$ vi /etc/conf/nginx/sites-enabled/

In here, I’d look for the ‘server’ block and add my redirection rules:

server {
  listen       80;
  root         /var/www/;

  # redirect iPhone/iPod users to the new iphone site
  if ($http_user_agent ~* '(iPhone|iPod|iPad)') {
    rewrite ^/$;

Then a simple nginx reload:

$ /etc/init.d/nginx reload

… and we were all set.