📁 Static File Serving
Basic Static File Serving
nginx
server {
listen 80;
server_name example.com;
# root specifies the root directory
root /var/www/mysite;
# Default index files
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}root vs alias Difference
nginx
# root: accessing /images/logo.png → looks for /var/www/html/images/logo.png
location /images/ {
root /var/www/html;
}
# alias: accessing /images/logo.png → looks for /var/www/static/logo.png
location /images/ {
alias /var/www/static/;
}💡 Tip: 💡 Easy way to remember:
rootmeans "append to the existing path,"aliasmeans "completely replace."
Enabling Gzip Compression
Gzip is like vacuum-packing a file — the transfer size shrinks, speed increases.
nginx
http {
gzip on; # Enable gzip
gzip_vary on; # Add Vary header
gzip_min_length 1024; # Don't compress anything smaller than 1KB
gzip_comp_level 6; # Compression level 1-9 (6 is the best balance)
gzip_types
text/plain
text/css
text/javascript
application/json
application/javascript
application/xml
image/svg+xml;
}Cache Control
nginx
# Static asset caching (CSS, JS, images)
location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg|woff2)$ {
expires 30d; # Cache for 30 days
add_header Cache-Control "public, no-transform";
access_log off; # Disable logging (reduces disk I/O)
}
# HTML files — no caching (ensures users always see the latest version)
location ~* \.html$ {
expires -1;
add_header Cache-Control "no-store, no-cache, must-revalidate";
}