Configuring Nginx for High-Performance Static Websites: Caching, Gzip, CORS, and Anti-Leech
This article explains how to configure Nginx for static sites by setting up caching policies, gzip compression, cross‑origin resource sharing, and anti‑hotlinking rules, while also providing practical code examples and discussing the underlying HTTP cache mechanisms.
Overview
This blog summarizes four key Nginx configuration topics—caching, gzip compression, cross‑origin resource sharing (CORS), and anti‑hotlinking—based on real‑world production experience, aiming to help readers improve site performance and security.
Cache
Proper cache settings reduce repeated server requests, shorten browser wait times, and enhance user experience.
Cache‑Control can be set using positive or negative values: a negative value means no-cache , while a positive value or zero means max-age=time .
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 Analysis
Steps:
User sends the first request; no cached copy exists.
Server responds with 200 and includes cache headers.
On subsequent requests, the browser checks its cache directory.
If no cached file is found, it repeats step 2.
If a cached file exists, the browser checks the Expires header.
If not expired, the cached file is used directly.
If expired, the browser validates the cached file using ETag and Last-Modified .
If unchanged, the server returns 304 and the cached file is used.
If changed, the server sends fresh data and updates the cache according to cache‑control directives.
Field Explanation
Browser Cache Process
Browsers distinguish between strong cache (using Expires and Cache-Control ) and negotiated cache (using ETag and Last-Modified ).
Strong cache rules: The server sends Expires and Cache-Control in the response headers; Cache-Control has higher priority.
Expires: HTTP/1.0 header indicating an absolute expiration time; superseded by Cache-Control in HTTP/1.1 due to clock‑skew issues.
Cache-Control parameters: Example configurations are shown below.
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 domains to access resources.
server {
listen 80;
server_name www.stark.com;
location / {
# Allow any origin or specify domains
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;
# Preflight request 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 configurations go here
}
}Anti‑hotlinking checks the Referer header to prevent unauthorized sites from using your static resources.
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;
}
}
}Promotional Content (Brief)
The author also promotes a ChatGPT‑focused community, offering paid memberships, free ChatGPT accounts, and various AI‑related resources, but these sections are unrelated to the technical tutorial.
For readers interested only in the Nginx configuration, the above sections provide the essential knowledge and practical code snippets.
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.