Hero Image

Quick Hacks

Quick Hacks

nginx is very powerful, and has a lot of information readily available in variables. You can easily make use of them:

Quick and easy display of remote IP-address (hi curl).

location = /ip {
    default_type text/plain;
    expires -1;
    return 200 "$remote_addr\n";
}

This is great to use with cURL on the command-line:

lxc :: ~ » curl https://example.com/ip
2001:db8:2::1

Connection information in JSON-format to use on site.

This is what I use in the footer of this page (scroll all the way down). You can let nginx return all kinds of information about your connection, and then use it in your pages.

location = /info.json {
    default_type application/json;
    expires -1;
    return 200 '{"server": "$hostname", "ssl_protocol": "$ssl_protocol", "ssl_cipher": "$ssl_cipher", "remote_addr": "$remote_addr", "http2": "$http2", "server_protocol": "$server_protocol"}';
}

Which results in something like this:

lxc :: ~ » curl -s https://example.com/info.json | jq .
{
  "server": "lb",
  "ssl_protocol": "TLSv1.2",
  "ssl_cipher": "ECDHE-ECDSA-AES256-GCM-SHA384",
  "remote_addr": "2001:db8:2::1",
  "http2": "h2",
  "spdy": "",
  "server_protocol": "HTTP/2.0"
}
lxc :: ~ »

Caching ("expires") with a map{}

Often an overlooked feature, but you can use a map{} with expires. This provides an easy way to set multiple caching expiries for different MIME-types in one go:

map $sent_http_content_type $expires {
    default         7d;

    text/css        1y;
    text/html       off;
    text/plain      off;

    application/javascript  1y;
    application/json    off;
    application/rss+xml off;
}

server {
    location /assets {
        expires $expires;
    }
}

Add/remove www. from site URL.

Some people really want their site to be accessed on www.example.com, some really want it accessed without. For some, it depends on the domain in question (like me). Well, good news: You can use regular expressions to make your life easier.

Do NOT use 301-redirects (permanent) for this, only 302 (temporary).

Add www. to all site URLs.

server {
        server_name ~^(?!www\.);

        location / {
                return 302 $scheme://www.$host$request_uri;
        }
}

Remove www. from all site URLs.

server {
        server_name ~^www\.(?<domain>.*);

        location / {
                return 302 $scheme://$domain$request_uri;
        }
}

Remove www. from selected site URLs.

For my own site, I want the finalx.* domains to be accessed without www. in the name. My other domains can be accessed with both (and yes, arguably I should stick with a single domain...).

server {
        server_name ~^www\.finalx\.(?<tld>.*);

        location / {
                return 302 $scheme://finalx.$tld$request_uri;
        }

}