Master Nginx Static Site Performance: Caching, Gzip, CORS & Anti‑Hotlinking
This article explains how to configure Nginx for high‑performance static sites by setting up effective browser caching, enabling gzip compression, handling CORS headers, and preventing hotlinking, complete with code examples, header details, and step‑by‑step principles.
Overview
This blog summarizes practical solutions for configuring Nginx static sites, covering caching, gzip compression, CORS, and anti‑hotlinking based on real‑world production experience.
Nginx Configuring High‑Performance Static Site
Cache
Proper cache settings let browsers reuse previously fetched resources, reducing server round‑trips, lowering latency, and improving user experience.
Cache‑Control can be set to no-cache (negative value) or max-age=time (positive value or zero).
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 daysPrinciple
Principle and steps:
User sends the first request; the browser has no cached copy.
Server responds with 200 and includes cache‑related headers.
On subsequent requests the browser checks its local cache for the resource.
If the file is missing, the request follows step 2.
If the file exists, the browser evaluates the Expires header.
If not expired, the cached file is served directly.
If expired, the browser checks whether the resource changed using ETag or Last‑Modified.
If unchanged, the server returns 304 and the browser uses the cached file.
If changed, the browser fetches a fresh copy and stores it according to the cache policy.
Cache Header Details
Strong cache rules: The server sends Expires and Cache‑Control in the response headers; Cache‑Control takes precedence.
Expires: HTTP/1.0 field indicating an absolute expiration time; superseded by Cache‑Control in HTTP/1.1 because client/server clock differences can invalidate Expires.
Cache‑Control parameters: Example configurations for static assets.
location ~* \.(css|js)$ {
expires 7d;
add_header Cache-Control "public";
}Alternative configuration:
location ~* \.(css|js)$ {
expires 600;
add_header Cache-control max-age=800;
}Sample response headers from a browser request:
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
Connection: keep-alive
ETag: "66b5e95c-2c7"
Expires: Mon, 12 Aug 2024 12:46:58 GMT
Cache-Control: max-age=86400
Cache-Control: publicGzip Module
Enabling gzip compression reduces the amount of data transferred, speeding up page loads.
location ~ .*\.(jpg|gif|png|js)$ {
gzip on;
gzip_http_version 1.1;
gzip_comp_level 2; # compression level 1‑9
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
These settings improve security by allowing only authorized origins and preventing other sites from hotlinking your static resources.
server {
listen 80;
server_name www.stark.com;
location / {
# Allow specific origins (or 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;
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;
}
}
}Anti‑hotlinking example using the Referer header:
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;
}
}
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
