Nginx Configuration
Nginx Configuration Nginx is a high-performance web server and reverse proxy. Its event-driven architecture makes it highly efficient for serving static content…
Nginx Configuration
Nginx is a high-performance web server and reverse proxy. Its event-driven architecture makes it highly efficient for serving static content, terminating SSL, and proxying to application servers.
Core Config Structure
# /etc/nginx/nginx.conf — main config
user nginx;
worker_processes auto; # one worker per CPU core
pid /var/run/nginx.pid;
events {
worker_connections 1024; # max simultaneous connections per worker
multi_accept on; # accept all pending connections at once
use epoll; # Linux: efficient event notification
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Logging format
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log warn;
# Performance
sendfile on; # zero-copy file transfer
tcp_nopush on; # batch send headers
tcp_nodelay on; # disable Nagle algorithm
keepalive_timeout 65; # keep connections open for 65s
# Gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied any;
gzip_comp_level 6;
gzip_types
text/plain text/css text/xml application/json
application/javascript application/rss+xml
application/atom+xml image/svg+xml;
# Include site configs
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}Server Blocks & Location Matching
# Location matching priority (highest to lowest):
# 1. = exact match location = /favicon.ico
# 2. ^~ prefix (no regex) location ^~ /images/
# 3. ~ case-sensitive regex location ~ \.php$
# 4. ~* case-insensitive rx location ~* \.(jpg|png|gif)$
# 5. / prefix (fallback) location /
server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;
index index.html index.htm;
# Exact match — served instantly, no further checks
location = /favicon.ico {
access_log off;
log_not_found off;
}
# Static assets — long cache, served directly
location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg|woff2)$ {
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
# PHP processing via FastCGI
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
# SPA fallback — serve index.html for all unmatched routes
location / {
try_files $uri $uri/ /index.html;
}
# Custom error pages
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}SSL & HTTPS with Let's Encrypt
# Force HTTP -> HTTPS redirect
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com www.example.com;
# SSL certificate (from Let's Encrypt / certbot)
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# Modern SSL settings
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off; # let client choose (TLS 1.3)
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off; # forward secrecy
# OCSP stapling (faster cert validation)
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=300s;
# Security headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header X-Frame-Options DENY always;
add_header X-Content-Type-Options nosniff always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'" always;
location / {
root /var/www/html;
try_files $uri $uri/ /index.html;
}
}CLI Commands
# Test configuration syntax (always do before reload!)
nginx -t
nginx -T # test and dump full resolved config
# Control nginx process
nginx -s reload # graceful reload (no downtime)
nginx -s reopen # reopen log files (after rotation)
nginx -s quit # graceful shutdown (wait for connections)
nginx -s stop # fast shutdown
# Systemd
systemctl start nginx
systemctl enable nginx # start on boot
systemctl reload nginx # same as nginx -s reload
systemctl status nginx
journalctl -u nginx -f # follow logs
# Certbot (Let's Encrypt SSL)
certbot --nginx -d example.com -d www.example.com
certbot renew --dry-run
certbot renew # usually run via cron/systemd timer
# Key file locations
# /etc/nginx/nginx.conf main config
# /etc/nginx/sites-available/ available site configs
# /etc/nginx/sites-enabled/ symlinks to active configs
# /etc/nginx/conf.d/ additional configs
# /var/log/nginx/access.log access logs
# /var/log/nginx/error.log error logs
# Enable a site (Debian/Ubuntu pattern)
ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/myapp
nginx -t && systemctl reload nginx