Installation & Setup
Install Nginx
bash
1# Ubuntu / Debian2sudo apt update3sudo apt install -y nginx4
5# Fedora / RHEL6sudo dnf install -y nginx7
8# macOS (Homebrew)9brew install nginx10
11# Verify12nginx -v13nginx -V # Show compile options and modulesStart & Stop
bash
1# Linux (systemd)2sudo systemctl start nginx3sudo systemctl stop nginx4sudo systemctl restart nginx5sudo systemctl reload nginx # Reload config without downtime6sudo systemctl enable nginx7sudo systemctl status nginx8
9# macOS10brew services start nginx11
12# Direct commands13nginx # Start server14nginx -s stop # Fast shutdown15nginx -s quit # Graceful shutdown16nginx -s reload # Reload config17nginx -s reopen # Reopen log files18
19# Test configuration before applying20sudo nginx -t # Test syntax21sudo nginx -T # Test + dump full configImportant Paths & Config Files
bash
1# Ubuntu / Debian2/etc/nginx/nginx.conf # Main config3/etc/nginx/sites-available/ # Available virtual hosts4/etc/nginx/sites-enabled/ # Enabled virtual hosts5/etc/nginx/snippets/ # Reusable config snippets6/etc/nginx/conf.d/ # Additional configs7/var/log/nginx/ # Log directory8/var/log/nginx/access.log # Access log9/var/log/nginx/error.log # Error log10/var/www/html/ # Default web root11
12# Fedora / RHEL13/etc/nginx/nginx.conf14/etc/nginx/conf.d/ # Additional configs15/var/log/nginx/16
17# macOS (Homebrew)18/opt/homebrew/etc/nginx/nginx.conf # Apple Silicon19/usr/local/etc/nginx/nginx.conf # Intel20
21# Default config structure22# /etc/nginx/nginx.conf23user nginx;24worker_processes auto;25error_log /var/log/nginx/error.log;26pid /run/nginx.pid;27
28events {29 worker_connections 1024;30}31
32http {33 include /etc/nginx/mime.types;34 default_type application/octet-stream;35
36 log_format main '$remote_addr - $remote_user [$time_local] "$request" '37 '$status $body_bytes_sent "$http_referer" '38 '"$http_user_agent" "$http_x_forwarded_for"';39
40 access_log /var/log/nginx/access.log main;41
42 sendfile on;43 tcp_nopush on;44 keepalive_timeout 65;45 gzip on;46
47 include /etc/nginx/conf.d/*.conf;48 include /etc/nginx/sites-enabled/*;49}Virtual Hosts (Server Blocks)
Basic Virtual Host
nginx
1# /etc/nginx/sites-available/example.com2server {3 listen 80;4 listen [::]:80;5 server_name example.com www.example.com;6 root /var/www/example.com/public;7
8 index index.html index.htm index.php;9
10 location / {11 try_files $uri $uri/ /index.php?$query_string;12 }13
14 # PHP processing15 location ~ \.php$ {16 fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;17 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;18 include fastcgi_params;19 }20
21 # Static assets caching22 location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2|woff|ttf|svg)$ {23 expires 30d;24 add_header Cache-Control "public, immutable";25 }26
27 # Deny access to hidden files28 location ~ /\. {29 deny all;30 }31
32 access_log /var/log/nginx/example.com.access.log;33 error_log /var/log/nginx/example.com.error.log;34}Enable / Disable Virtual Host
bash
1# Enable site (Debian/Ubuntu)2sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/3sudo nginx -t4sudo systemctl reload nginx5
6# Disable site7sudo rm /etc/nginx/sites-enabled/example.com8sudo systemctl reload nginx9
10# List enabled sites11ls -la /etc/nginx/sites-enabled/12
13# Test specific config file14sudo nginx -t -c /etc/nginx/sites-available/example.comSSL / TLS (HTTPS)
Certbot (Let's Encrypt)
bash
1# Install certbot2sudo apt install -y certbot python3-certbot-nginx3
4# Obtain certificate (auto-configures Nginx)5sudo certbot --nginx -d example.com -d www.example.com6
7# Obtain certificate (standalone — stop Nginx first)8sudo certbot certonly --standalone -d example.com9
10# Obtain certificate (webroot)11sudo certbot certonly --webroot -w /var/www/example.com -d example.com12
13# Renew certificates14sudo certbot renew15sudo certbot renew --dry-run # Test renewal16
17# Check certificate expiry18sudo certbot certificates19openssl x509 -in /etc/letsencrypt/live/example.com/fullchain.pem -noout -dates20
21# Auto-renewal (cron)22echo "0 3 * * * root certbot renew --quiet" | sudo tee /etc/cron.d/certbot-renewSSL Configuration Snippet
nginx
1# /etc/nginx/snippets/ssl-params.conf2ssl_protocols TLSv1.2 TLSv1.3;3ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;4ssl_prefer_server_ciphers off;5
6ssl_session_timeout 1d;7ssl_session_cache shared:SSL:10m;8ssl_session_tickets off;9
10ssl_stapling on;11ssl_stapling_verify on;12
13add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;14add_header X-Frame-Options DENY always;15add_header X-Content-Type-Options nosniff always;16add_header X-XSS-Protection "1; mode=block" always;17add_header Referrer-Policy "strict-origin-when-cross-origin" always;HTTPS Virtual Host
nginx
1server {2 listen 443 ssl http2;3 listen [::]:443 ssl http2;4 server_name example.com www.example.com;5
6 ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;7 ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;8 include /etc/nginx/snippets/ssl-params.conf;9
10 root /var/www/example.com/public;11 index index.html index.php;12
13 location / {14 try_files $uri $uri/ /index.php?$query_string;15 }16}17
18# Redirect HTTP to HTTPS19server {20 listen 80;21 listen [::]:80;22 server_name example.com www.example.com;23 return 301 https://$server_name$request_uri;24}Reverse Proxy
Basic Reverse Proxy
nginx
1# Proxy to backend application (Node.js, Go, etc.)2server {3 listen 80;4 server_name app.example.com;5
6 location / {7 proxy_pass http://127.0.0.1:3000;8 proxy_http_version 1.1;9 proxy_set_header Upgrade $http_upgrade;10 proxy_set_header Connection "upgrade";11 proxy_set_header Host $host;12 proxy_set_header X-Real-IP $remote_addr;13 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;14 proxy_set_header X-Forwarded-Proto $scheme;15
16 proxy_connect_timeout 60s;17 proxy_send_timeout 60s;18 proxy_read_timeout 60s;19 proxy_buffering on;20 proxy_buffer_size 4k;21 proxy_buffers 8 4k;22 }23
24 # WebSocket support25 location /ws {26 proxy_pass http://127.0.0.1:3000;27 proxy_http_version 1.1;28 proxy_set_header Upgrade $http_upgrade;29 proxy_set_header Connection "upgrade";30 proxy_set_header Host $host;31 proxy_read_timeout 86400s;32 }33}Load Balancing
nginx
1# Upstream definition2upstream backend {3 server 10.0.0.1:8080 weight=3;4 server 10.0.0.2:8080 weight=2;5 server 10.0.0.3:8080 weight=1;6 server 10.0.0.4:8080 backup; # Backup server7
8 keepalive 32; # Connection pooling9}10
11# Round-robin (default)12upstream backend_rr {13 server 10.0.0.1:8080;14 server 10.0.0.2:8080;15 server 10.0.0.3:8080;16}17
18# IP hash (sticky sessions)19upstream backend_iphash {20 ip_hash;21 server 10.0.0.1:8080;22 server 10.0.0.2:8080;23 server 10.0.0.3:8080;24}25
26# Least connections27upstream backend_leastconn {28 least_conn;29 server 10.0.0.1:8080;30 server 10.0.0.2:8080;31 server 10.0.0.3:8080;32}33
34# Consistent hash (by request URI or custom key)35upstream backend_consistent {36 hash $request_uri consistent;37 server 10.0.0.1:8080;38 server 10.0.0.2:8080;39 server 10.0.0.3:8080;40}41
42# Use upstream in server block43server {44 listen 80;45 server_name app.example.com;46
47 location / {48 proxy_pass http://backend;49 proxy_set_header Host $host;50 proxy_set_header X-Real-IP $remote_addr;51 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;52 }53}Caching
Proxy Cache
nginx
1# Define cache path2proxy_cache_path /var/cache/nginx levels=1:23 keys_zone=my_cache:10m max_size=1g4 inactive=60m use_temp_path=off;5
6server {7 location / {8 proxy_pass http://backend;9 proxy_cache my_cache;10 proxy_cache_valid 200 302 10m;11 proxy_cache_valid 404 1m;12 proxy_cache_key "$scheme$request_method$host$request_uri";13 proxy_cache_use_stale error timeout updating http_500 http_502 http_503;14
15 add_header X-Cache-Status $upstream_cache_status;16 }17}FastCGI Cache (PHP)
nginx
1fastcgi_cache_path /var/cache/nginx/fastcgi2 levels=1:2 keys_zone=php_cache:10m max_size=1g inactive=60m;3
4server {5 location ~ \.php$ {6 fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;7 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;8 include fastcgi_params;9
10 fastcgi_cache php_cache;11 fastcgi_cache_valid 200 60m;12 fastcgi_cache_key "$scheme$request_method$host$request_uri";13 }14}Browser Cache
nginx
1# Static assets2location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2|woff|ttf|svg|eot)$ {3 expires 30d;4 add_header Cache-Control "public, immutable";5 access_log off;6}7
8# Cache-Control headers9location /api/ {10 add_header Cache-Control "no-store, no-cache, must-revalidate";11}Security
Rate Limiting
nginx
1# Define rate limit zones2limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;3limit_req_zone $binary_remote_addr zone=login_limit:10m rate=1r/s;4
5# Apply rate limits6location /api/ {7 limit_req zone=api_limit burst=20 nodelay;8 proxy_pass http://backend;9}10
11location /login {12 limit_req zone=login_limit burst=3 nodelay;13 proxy_pass http://backend;14}15
16# Limit connections per IP17limit_conn_zone $binary_remote_addr zone=conn_limit:10m;18
19location /download/ {20 limit_conn conn_limit 5; # Max 5 concurrent connections per IP21}Access Control
nginx
1# Allow specific IPs2location /admin/ {3 allow 10.0.0.0/8;4 allow 192.168.1.0/24;5 deny all;6 proxy_pass http://backend;7}8
9# HTTP Basic Auth10location /admin/ {11 auth_basic "Restricted Area";12 auth_basic_user_file /etc/nginx/.htpasswd;13 proxy_pass http://backend;14}15
16# Create htpasswd file17# sudo apt install -y apache2-utils18# sudo htpasswd -c /etc/nginx/.htpasswd adminSecurity Headers
nginx
1# Global headers2add_header X-Frame-Options DENY always;3add_header X-Content-Type-Options nosniff always;4add_header X-XSS-Protection "1; mode=block" always;5add_header Referrer-Policy "strict-origin-when-cross-origin" always;6add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'" always;7add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;8
9# HSTS (only add after confirming HTTPS works)10add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;Block Bad Bots
nginx
1# Block user agents2if ($http_user_agent ~* (scrapy|curl|wget|python-requests|go-http-client|java/|nikto|sqlmap)) {3 return 403;4}5
6# Block specific referers7valid_referers none blocked server_names *.google.com;8if ($invalid_referer) {9 return 403;10}Useful Patterns
Redirects
nginx
1# Redirect HTTP to HTTPS2return 301 https://$server_name$request_uri;3
4# Redirect www to non-www5return 301 https://$server_name$request_uri;6
7# Redirect non-www to www8return 301 http://www.$server_name$request_uri;9
10# Redirect all HTTP to HTTPS11server {12 listen 80;13 server_name _;14 return 301 https://$host$request_uri;15}Proxy Buffering
nginx
1proxy_buffering on;2proxy_buffer_size 4k; # First buffer (headers)3proxy_buffers 8 4k; # Response buffers4proxy_busy_buffers_size 8k; # Buffers while sending to clientProxy Timeout
nginx
1proxy_connect_timeout 60s; # Connection to backend2proxy_send_timeout 60s; # Sending request to backend3proxy_read_timeout 60s; # Reading response from backend4proxy_next_upstream error timeout http_502 http_503;5proxy_next_upstream_tries 3;Useful Commands
bash
1# Check Nginx status2curl -I http://localhost # Check if responding3curl -s -o /dev/null -w "%{http_code}" http://localhost # HTTP status code only4
5# Check active connections6curl http://localhost/nginx_status # Requires stub_status module7
8# Test SSL9openssl s_client -connect example.com:443 -servername example.com10
11# Check certificate details12openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null | openssl x509 -noout -text13
14# Find config errors15sudo nginx -t 2>&1 | grep -i error16
17# Check loaded modules18nginx -V 2>&1 | grep -o 'with-[a-z_-]*'19
20# Benchmark with ab (Apache Bench)21ab -n 1000 -c 10 http://localhost/22
23# Watch access log24tail -f /var/log/nginx/access.log25
26# Watch error log27tail -f /var/log/nginx/error.logTroubleshooting
bash
1# Configuration syntax error2sudo nginx -t # Shows exact line number and error3
4# 502 Bad Gateway5# Check if backend is running: curl http://127.0.0.1:30006# Check socket: ls -la /var/run/php/php8.2-fpm.sock7# Check permissions8
9# 413 Request Entity Too Large10client_max_body_size 50M; # In server or http block11
12# 504 Gateway Timeout13proxy_read_timeout 300s; # Increase timeout14
15# Permission denied16ls -la /var/www/ # Check ownership17chown -R www-data:www-data /var/www/ # Fix ownership18
19# Worker connections exceeded20worker_connections 1024; # Increase in events block21worker_rlimit_nofile 65535; # Increase file descriptor limit22
23# Log rotation24# Create /etc/logrotate.d/nginx25/var/log/nginx/*.log {26 daily27 missingok28 rotate 1429 compress30 delaycompress31 notifempty32 create 0640 www-data adm33 sharedscripts34 postrotate35 [ -f /var/run/nginx.pid ] && kill -USR1 $(cat /var/run/nginx.pid)36 endscript37}Output Formatting
Stub Status Module
nginx
1# /etc/nginx/conf.d/stub_status.conf2server {3 listen 127.0.0.1:8080;4 server_name localhost;5
6 location /nginx_status {7 stub_status;8 allow 127.0.0.1;9 deny all;10 }11}bash
1# Check status2curl http://127.0.0.1:8080/nginx_status3
4# Output:5# Active connections: 2916# server accepts handled requests7# 16630948 16630948 310704658# Reading: 6 Writing: 179 Waiting: 106Log Format Customization
nginx
1# JSON log format (for log aggregators)2log_format json_combined escape=json3 '{'4 '"time":"$time_iso8601",'5 '"remote_addr":"$remote_addr",'6 '"request":"$request",'7 '"status":$status,'8 '"body_bytes_sent":$body_bytes_sent,'9 '"request_time":$request_time,'10 '"upstream_response_time":"$upstream_response_time",'11 '"http_referer":"$http_referer",'12 '"http_user_agent":"$http_user_agent"'13 '}';14
15access_log /var/log/nginx/access.log json_combined;