Configuring Nginx for High‑Performance Static Websites: Caching, Gzip, CORS, and Anti‑Hotlinking
This article explains how to configure Nginx for high‑performance static sites by setting up proper caching rules, enabling gzip compression, handling cross‑origin requests, and preventing hotlinking, complete with practical code examples and detailed workflow analysis.
Overview: This blog summarizes four key Nginx configuration topics—caching, gzip compression, cross‑origin resource sharing (CORS), and anti‑hotlinking—based on production practice, aiming to help readers improve site performance and security.
Cache
By configuring a reasonable cache mechanism, browsers can reuse previously fetched resources without repeatedly contacting the server, reducing latency and enhancing user experience.
Cache directives can use positive or negative values for the Expires header, which in turn influences the Cache-Control value. 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:
When a user first requests a resource, the browser has no cached copy and must send a request to the server.
The server responds with a 200 status and includes caching headers (e.g., Expires , Cache-Control ).
On subsequent requests, the browser checks its local cache. If a valid, unexpired entry exists, it serves the resource locally.
If the cached entry is expired, the browser validates it using ETag or Last-Modified . If unchanged, the server returns 304 and the browser uses the cached copy; otherwise, a fresh response is fetched.
Cache‑Control rules: Cache-Control has higher priority than Expires . The Cache‑Conctrol header (typo in original) controls strong caching, while Expires is an older HTTP/1.0 mechanism that can be unreliable due to client‑server time differences.
Gzip Module
Enabling gzip compression reduces the amount of data transferred over HTTP, speeding up page loads.
location ~ .*\.(jpg|gif|png|js)$ {
gzip on;
gzip_http_version 1.1;
gzip_comp_level 2; # compression level, default 1, max 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
CORS and anti‑hotlinking configurations improve security by allowing only authorized domains to access resources.
server {
listen 80;
server_name www.stark.com;
location / {
# Allow any origin or specify specific domains
add_header 'Access-Control-Allow-Origin' 'http://stark1.com https://stark2.com';
# Allowed methods
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
# Allowed headers
add_header 'Access-Control-Allow-Headers' 'User-Agent,Keep-Alive,Content-Type';
# Max age for preflight request caching
add_header 'Access-Control-Max-Age' 1728000;
# Handle preflight OPTIONS request
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 ensure that static resources are not being requested from unauthorized sites.
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;
}
}
}The article concludes with a call for discussion, sharing of experiences, and promotion of a community offering ChatGPT resources, but the technical sections provide concrete, reusable Nginx configurations for developers and operations engineers.
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.