Web service and reverse proxy with the speedy nginx

Static Content and Caching

With this basic setup working, the next step is for nginx to statically serve some images. This step will allow you to tune your back-end httpd processes for dynamic content serving. I'll also serve images with an expires header of 30 days, which will cut down on the number of requests a client needs to make for common images that rarely change. To accomplish this, add the following to your server context:

location ~* ^.+\.(jpg|jpeg|gif|png)$ {
       root      /path/to/www;
       expires   30d;
}

If you'd like to disable logging for images requests, add the following line to the configuration:

access_log off;

Next, nginx will gzip some output received from the httpd back-ends before sending it to the browser. The nginx server will only gzip certain content based on mime type and will completely disable gzip for some known-broken browsers. Add the code in Listing 3 to your server context.

Listing 3

gzip in nginx.conf

01 gzip                    on;
02 gzip_http_version       1.0;
03 gzip_vary               on;
04 gzip_min_length 1100;
05 gzip_buffers            16 8k;
06 gzip_comp_level 5;
07 gzip_proxied            any;
08 gzip_types      text/plain text/css application/javascript text/javascript text/xml application/x-javascript;
09 gzip_disable            "MSIE [1-6]\.";

If you'd like to cache some of your dynamic content with nginx, you have two options; file based or memcached based. If you're considering using nginx to cache content, be careful how you cache content that differs based on whether a visitor is logged in or not. To enable the file-based cache, add the following to the http context in your configuration file:

proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=one:10m;

The levels parameter sets the number of subdirectories for the cache, and the key and filename are an md5 of the proxyied URL, resulting in filenames similar to /data/nginx/cache/c/29/b7f54b2df7773722d382f4809d65029c.

With the cache path set in the http context, you can now setup your cache in the http, server, or location context. To cache all 200 and 302 responses for 30 minutes and all 404 responses for 5 minutes, add the following:

proxy_cache one;
proxy_cache_valid 200 302 30m;
proxy_cache_valid 404 5m;

If you'd prefer to use memcached for your cache, it's almost as easy (see Listing 4).

Listing 4

memcached nginx.conf

01 server {
02   location / {
03     set $memcached_key $uri;
04     memcached_pass     name:11211;
05     default_type       text/html;
06     error_page         404 @fallback;
07   }
08
09   location @fallback {
10     proxy_pass cluster;
11   }
12 }

Server Statistics

Many monitoring systems support the httpd mod_status module to gather and trend statistics. The stub_status module serves a similar role with nginx. This module is not compiled by default and must be enabled with the --with-http_stub_status_module configure argument. Once the module is compiled in, add the code in Listing 5 to your configuration file. An HTTP request to domain.com/nginx_status will return a plain text response in the format shown in Listing 6.

Listing 5

stub_status nginx.conf

01 location /nginx_status {
02         stub_status             on;
03         access_log              off;
04         allow                   TRUSTED.IP.ADDRESSES
05         deny                    all;
06 }

Listing 6

nginx_status output

01 Active connections: 291
02 server accepts handled requests
03   16630948 16630948 31070465
04 Reading: 6 Writing: 179 Waiting: 106
05 This server has 291 active connections, has accepted and handled 16630948 connections while serving 31070465 requests...

Additional Modules

The httpd mod_rewrite module is used by many sites. While nginx does have a rewrite module, its syntax is slightly different from the one for httpd. The nginx wiki has the full details [4].

One example of rewrite feature is a simple rewrite to enable SEO-friendly member pages:

rewrite ^/users/(.*)$  /user.php?user=$1? last;

A more complicated rewrite uses an if condition to redirect your visitors to a consistent domain:

if ($host ~* www\. (.*)) {
   set $host_without_ www $1;
   rewrite ^(.*)$ http://$host_ without_www$1 permanent;
}

The GeoIP module creates variables based on the IP address of the client matched against the MaxMind GeoIP binary files. The nginx GeoIP module has two prerequisites – libGeoIP and the MaxMind GeoIP database(s). The latest libGeoIP is available from the MaxMind site [5], but keep in mind that many distributions have libGeoIP in their package repositories.

Add the following two lines to your http context to enable the GeoIP module.

geoip_country GeoIP.dat;
geoip_city GeoLiteCity.dat;

You will now have the variables listed on http://wiki.nginx.org/NginxHttpGeoIPModule at your disposal. One common use case for the GeoIP module is to use the $geoip_country_code variable to send requests to different proxy upstreams based on country. If you'd like to pass the GeoIP information to you httpd back-ends, add the following to your proxy configuration:

proxy_set_header HTTP_GEO $geo;

Table 2 shows some additional nginx modules, along with a brief overview of their functionality.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Fast Web Servers

    This month we look at some alternative web servers and show you some smart Apache techniques.

  • Media Sharing with MediaCrush

    Sharing videos or images doesn't always require a full-fledged YouTube or Flickr clone. Sometimes all you want is a quick place to upload, so you can link to your media or share it online. MediaCrush gives you just that, as well as other interesting perks.

  • Apache Load Balancing

    Today's web performance and availability requirements make load balancing indispensable. In this article, we show you how to set up an effective load balancing system using features built into the Apache web server.

  • Charly's Column: GeoIP Lookup

    The global village is big enough to want to find out where your friend and enemies have set up camp. Charly offers a quick IP-based introduction to geography.

  • Tech Tools
    • SkySQL Merges with Makers of MariaDB
    • AMD Announces New Custom Chip Operation
    • New Supermicro Storage Solution
    • SUSE Studio 1.3
    • Nginx 1.4 Released
comments powered by Disqus

Direct Download

Read full article as PDF:

028-031_nginx.pdf (1.15 MB)

News