Boost Static Site Performance: Master Nginx Caching, Gzip, CORS, and Anti‑Hotlinking

This guide consolidates practical Nginx configurations for static sites, covering cache control with Expires and Cache‑Control headers, gzip compression settings, cross‑origin resource sharing rules, and referer‑based anti‑hotlinking techniques, each illustrated with real‑world examples and command snippets.

Liangxu Linux
Liangxu Linux
Liangxu Linux
Boost Static Site Performance: Master Nginx Caching, Gzip, CORS, and Anti‑Hotlinking

Overview

The article summarizes common Nginx configuration techniques for high‑performance static websites, focusing on four key areas—caching, gzip compression, cross‑origin resource sharing (CORS), and anti‑hotlinking—based on issues encountered in production.

Caching

Proper cache directives let browsers reuse previously fetched resources, reducing round‑trips and improving user experience. The Expires header can be set with a positive or negative time value; a negative value results in no‑cache, while zero or a positive value yields max‑age=time. Example:

location ~* \.(jpg|jpeg|png|gif)$ {
    expires 30d;
}
# expires 30s;   # cache 30 seconds
# expires 30m;   # cache 30 minutes
# expires 2h;    # cache 2 hours
# expires 30d;   # cache 30 days

The caching workflow is:

User requests a resource for the first time; no local cache exists.

Server responds with 200 and includes caching headers.

On subsequent requests, the browser checks its cache directory.

If a cached file is missing, the request proceeds as in step 2.

If a cached file exists, the browser evaluates the Expires header.

If not expired, the cached file is served directly.

If expired, the browser compares ETag and Last‑Modified to determine freshness.

If unchanged, the server returns 304 Not Modified and the browser uses the cached copy.

If changed, the browser fetches a fresh copy and stores it according to the cache‑control policy.

Key header fields:

Expires : HTTP/1.0 expiration timestamp; superseded by Cache‑Control in HTTP/1.1 due to clock‑skew issues.

Cache‑Control : Preferred directive; its max‑age parameter overrides Expires.

Typical static‑file configurations:

location ~* \.(css|js)$ {
    expires 7d;
    add_header Cache-Control "public";
}
location ~* \.(css|js)$ {
    expires 600;
    add_header Cache-Control max-age=800;
}

Sample 304 response headers captured from a browser:

HTTP/1.1 304 Not Modified
Server: nginx
Date: Sun, 11 Aug 2024 12:46:58 GMT
Last-Modified: Fri, 09 Aug 2024 10:03:08 GMT
ETag: "66b5e95c-2c7"
Expires: Mon, 12 Aug 2024 12:46:58 GMT
Cache-Control: max-age=86400
Cache-Control: public

Gzip Compression

Enabling gzip reduces the size of HTTP responses, speeding up page loads. A typical configuration enables gzip for common text and image types and sets a moderate compression level:

location ~ .*\.(jpg|gif|png|js)$ {
    gzip on;
    gzip_http_version 1.1;
    gzip_comp_level 2; # 1‑9, default 1
    gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif img/png;
}

CORS and Anti‑Hotlinking

CORS headers allow legitimate cross‑origin requests, while anti‑hotlinking checks the Referer header to block unauthorized use of static assets.

server {
    listen 80;
    server_name www.stark.com;

    location / {
        # Allow specific origins (use * for any)
        add_header 'Access-Control-Allow-Origin' 'http://stark1.com https://stark2.com';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'User-Agent,Keep-Alive,Content-Type';
        add_header 'Access-Control-Max-Age' 1728000;

        # Pre‑flight OPTIONS handling
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'User-Agent,Keep-Alive,Content-Type';
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;
        }
        # Other server configuration goes here
    }
}

Anti‑hotlinking example using valid_referers and a conditional return:

server {
    listen 80;
    server_name yourdomain.com;

    location / {
        root /path/to/your/files;
        valid_referers none blocked server_names *.yourdomain.com;
        if ($invalid_referer) {
            return 403;
        }
    }
}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

cachingCORSNGINXGzipstatic siteanti-hotlinking
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.