Sunday, January 23, 2011

Conditionally changing MIME type in nginx

I'm using nginx as a frontend to Rails. All pages are cached as .html files on disk, and nginx serves these files if they exist. I want to send the correct MIME type for feeds (application/rss+xml), but the way I have so far is quite ugly, and I'm wondering if there is a cleaner way.

Here is my config:

location ~ /feed/$ {
  types {}
  default_type application/rss+xml;
  root /var/www/cache/;
  if (-f request_filename/index.html) {
    rewrite (.*) $1/index.html break;
  }
  if (-f request_filename.html) {
    rewrite (.*) $1.html break;
  }
  if (-f request_filename) {
    break;
  }
  if (!-f request_filename) {
    proxy_pass http://mongrel;
    break;
  }

}

location / {
  root /var/www/cache/;
  if (-f request_filename/index.html) {
    rewrite (.*) $1/index.html break;
  }
  if (-f request_filename.html) {
    rewrite (.*) $1.html break;
  }
  if (-f request_filename) {
    break;
  }
  if (!-f request_filename) {
    proxy_pass http://mongrel;
    break;
  }
}

My questions:

  1. Is there a better way to change the MIME type? All cached files have .html extensions and I cannot change this.
  2. Is there a way to factor out the if conditions in /feed/$ and /? I understand that I can use include, but I'm hoping for a better way. Putting part of the config in a different file is not that readable.
  3. Can you spot any bugs in the if conditions?

I'm using nginx 0.6.32 (Debian Lenny). I prefer to use the version in APT.

Thanks.

  • My advice: move on to Nginx 0.7.x and use try_files and proxy_cache, it will simplify your setup a lot. try_files was designed to factor out repetitive if (-f statements:

    location / {
      try_files $uri/index.html $uri.html $uri @mongrel
    }
    
    location @mongrel {
      proxy_pass http://mongrel;
    }
    

    As of MIME type, if you'd use proxy_cache, you could return MIME type from your application and Nginx would cache it.

    From Alaz

0 comments:

Post a Comment