Nginx tips and tricks

Redirect root of domain to somewhere else:

server {
    server_name zombix.org www.zombix.org;
    location = / {
       rewrite ^ http://about.me/z0mbix permanent;
    }
}

Redirect www.domain.com to domain.com:

server {
    server_name www.z0mbix.io;
    return 301 $scheme://z0mbix.io$request_uri;
}

Redirect all HTTP requests to HTTPS:

server {
    server_name z0mbix.io;
    return 301 https://$server_name$request_uri;
}

Configure a health check location:

location = /health/ping {
    add_header X-Health ok;
    return 200 "ok";
}

Add a trailing slash to any urls that are missing a trailing slash

rewrite ^(.*[^/])$ $1/ permanent;

Or, if you prefer urls without trailing slashes, use the following rewrite instead:

rewrite ^/(.*)/$ /$1 permanent;

Disable hot-linking using file extension regex:

location ~ .(gif|png|jpe?g)$ {
    valid_referers none blocked z0mbix.io *.z0mbix.io;
    if ($invalid_referer) {
        return 403;
    }
}

Disable hot-linking using directory

location /images/ {
    valid_referers none blocked z0mbix.io *.z0mbix.io;
    if ($invalid_referer) {
        return 403;
    }
}

Cache files:

location /static/ {
    expires 30d;
}

Serve an empty tracking pixel:

location /img/1px.gif {
    empty_gif;
    access_log off;
}

Deny access to a file:

location ^~ /config/config.ini { deny all; }

Don't serve dot files (.htaccess etc.):

location /. {
    return 404;
}

Enable HTTP basic authentication:

location /reports/ {
    auth_basic "Restricted Reports Area";
    auth_basic_user_file /etc/nginx/htpasswd;
    autoindex on;
}

Create the 'reports' user with:

# htpasswd -c /etc/nginx/htpasswd reports

Proxy to different backends depending on a cookie:

if ($http_cookie ~ "stack=green" ) {
    add_header X-Stack green;
    proxy_pass http://1.1.1.1$request_uri;
    break;
}

if ($http_cookie ~ "stack=blue" ) {
    add_header X-Stack blue;
    proxy_pass http://2.2.2.2$request_uri;
    break;
}

All these examples are based on my testing with nginx versions 1.2 - 1.8.