env.dev

Nginx Cheat Sheet — Server Blocks, Reverse Proxy, SSL & Performance Tuning

Quick reference for Nginx: service management, server blocks, reverse proxy, load balancing, SSL/TLS, location matching, logging, and performance tuning.

Last updated:

Nginx quick-reference covering essential commands, server block configuration, reverse proxy setup, load balancing, SSL/TLS, logging, and performance tuning. Organized by workflow so you can find the right directive or command instantly. Whether you are serving static files, proxying to a backend application, or configuring HTTPS — this cheat sheet has you covered.

How Do You Manage the Nginx Service?

CommandDescription
sudo systemctl start nginxStart the Nginx service
sudo systemctl stop nginxStop the Nginx service
sudo systemctl restart nginxRestart Nginx (drops connections)
sudo systemctl reload nginxReload config without downtime
sudo systemctl enable nginxEnable Nginx to start on boot
sudo systemctl status nginxCheck service status
nginx -tTest configuration for syntax errors
nginx -TTest and print the full merged configuration
nginx -s reloadSend reload signal directly to Nginx
nginx -s quitGraceful shutdown (finishes active requests)
nginx -s stopImmediate shutdown
nginx -vPrint Nginx version
nginx -VPrint version, compiler options, and modules

Key File Locations

PathDescription
/etc/nginx/nginx.confMain configuration file
/etc/nginx/conf.d/Additional config files (included by default)
/etc/nginx/sites-available/Available server block configs (Debian/Ubuntu)
/etc/nginx/sites-enabled/Symlinks to active server blocks
/etc/nginx/mime.typesMIME type mappings
/var/log/nginx/access.logAccess log (all requests)
/var/log/nginx/error.logError log
/usr/share/nginx/html/Default document root

How Do You Configure a Basic Server Block?

DirectiveDescriptionExample
listenPort and optional address to listen onlisten 80; or listen 443 ssl;
server_nameDomain names this block responds toserver_name example.com www.example.com;
rootDocument root directory for serving filesroot /var/www/example.com/html;
indexDefault files to serve for directory requestsindex index.html index.htm;
location /Match requests by URI pathlocation /images/ { ... }
try_filesTry paths in order, fall back to last argtry_files $uri $uri/ /index.html;
error_pageCustom error pageserror_page 404 /404.html;
returnReturn a status code or redirectreturn 301 https://$host$request_uri;

How Do You Set Up a Reverse Proxy?

DirectiveDescriptionExample
proxy_passForward requests to a backend serverproxy_pass http://localhost:3000;
proxy_set_header HostPass the original Host headerproxy_set_header Host $host;
proxy_set_header X-Real-IPPass the client real IPproxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-ForPass the forwarded-for chainproxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-ProtoPass the original protocolproxy_set_header X-Forwarded-Proto $scheme;
proxy_http_versionSet HTTP version for backendproxy_http_version 1.1;
proxy_read_timeoutTimeout for reading backend responseproxy_read_timeout 90s;
proxy_connect_timeoutTimeout for connecting to backendproxy_connect_timeout 30s;
proxy_bufferingEnable or disable response bufferingproxy_buffering off;

Load Balancing

Directive / MethodDescriptionExample
upstream <name> { ... }Define a group of backend serversupstream backend { server 10.0.0.1:8080; }
server <addr>:<port>Add a server to the upstream groupserver 10.0.0.2:8080;
(default) round-robinDistribute requests evenly in orderNo directive needed — default behavior
least_connRoute to server with fewest active connectionsupstream backend { least_conn; ... }
ip_hashSticky sessions based on client IPupstream backend { ip_hash; ... }
weight=NAssign relative weight to a serverserver 10.0.0.1:8080 weight=3;
max_fails=NMark server down after N failed attemptsserver 10.0.0.1:8080 max_fails=3;
fail_timeout=NsTime window for max_fails and downtime durationserver 10.0.0.1:8080 fail_timeout=30s;
backupOnly use this server when all others are downserver 10.0.0.3:8080 backup;
downMark a server as permanently unavailableserver 10.0.0.4:8080 down;

How Do You Configure SSL/TLS?

DirectiveDescriptionExample
listen 443 sslEnable SSL on port 443listen 443 ssl;
ssl_certificatePath to the SSL certificate filessl_certificate /etc/ssl/certs/site.pem;
ssl_certificate_keyPath to the private key filessl_certificate_key /etc/ssl/private/site.key;
ssl_protocolsAllowed TLS protocol versionsssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphersAllowed cipher suitesssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:...';
ssl_prefer_server_ciphersPrefer server cipher orderssl_prefer_server_ciphers on;
ssl_session_cacheEnable SSL session cachingssl_session_cache shared:SSL:10m;
ssl_session_timeoutTimeout for cached SSL sessionsssl_session_timeout 10m;
ssl_staplingEnable OCSP staplingssl_stapling on;

Location Block Matching

ModifierDescriptionExample
(none)Prefix match — lowest prioritylocation /api { ... }
^~Prefix match — skips regex if matchedlocation ^~ /static/ { ... }
=Exact match — highest prioritylocation = /health { return 200; }
~Case-sensitive regex matchlocation ~ \.php$ { ... }
~*Case-insensitive regex matchlocation ~* \.(jpg|png|gif)$ { ... }

Logging and Monitoring

DirectiveDescriptionExample
access_logSet path and format for the access logaccess_log /var/log/nginx/app.access.log;
error_logSet path and level for the error logerror_log /var/log/nginx/app.error.log warn;
log_formatDefine a custom log formatlog_format main '$remote_addr - $request ...';
access_log offDisable access logging for a locationaccess_log off;
stub_statusEnable basic status page (active connections)location /nginx_status { stub_status; }

Performance Tuning

DirectiveDescriptionExample
worker_processesNumber of worker processes (auto = match CPU cores)worker_processes auto;
worker_connectionsMax simultaneous connections per workerworker_connections 1024;
sendfileUse kernel sendfile for static file servingsendfile on;
tcp_nopushSend headers and file in one packettcp_nopush on;
tcp_nodelayDisable Nagle algorithm for keep-alive connectionstcp_nodelay on;
gzipEnable gzip compressiongzip on;
gzip_typesMIME types to compressgzip_types text/plain application/json;
gzip_min_lengthMinimum response size to compressgzip_min_length 256;
keepalive_timeoutTimeout for keep-alive connectionskeepalive_timeout 65;
client_max_body_sizeMaximum allowed request body sizeclient_max_body_size 10m;

Frequently Asked Questions

How do you redirect HTTP to HTTPS in Nginx?

Add a server block listening on port 80 with: return 301 https://$host$request_uri; — this sends a permanent redirect for all HTTP requests to their HTTPS equivalent.

What is the difference between nginx -s reload and systemctl restart nginx?

nginx -s reload sends a signal to gracefully reload configuration without dropping active connections. systemctl restart nginx fully stops and restarts the process, which briefly drops all connections.

How does Nginx decide which server block handles a request?

Nginx first matches the listen directive (IP and port), then compares the Host header against server_name values. Exact matches take priority, followed by leading wildcards, trailing wildcards, and finally regex patterns. If nothing matches, the default_server block handles the request.

How do you serve a single-page application (SPA) with Nginx?

Use try_files $uri $uri/ /index.html; inside your location / block. This tries the requested file first, then the directory, and falls back to index.html so your client-side router can handle the route.

What does proxy_pass do in Nginx?

proxy_pass forwards incoming requests to a specified backend server (e.g., a Node.js or Python app). It is the core directive for configuring Nginx as a reverse proxy. You place it inside a location block and point it to the backend address, such as proxy_pass http://localhost:3000;.

How do you enable gzip compression in Nginx?

Add gzip on; to your http or server block, then specify which MIME types to compress with gzip_types (e.g., text/plain, application/json, text/css). Set gzip_min_length to avoid compressing very small responses. This reduces bandwidth usage and improves page load times.