DevTools

Cheatsheet Nginx

Servidor web, reverse proxy e balanceador de carga de alta performance

Back to languages
Nginx
24 cards found
Categories:
Versions:

Basic Configuration


4 cards
Config Structure
# /etc/nginx/nginx.conf
worker_processes auto;

events {
  worker_connections 1024;
}

http {
  include /etc/nginx/conf.d/*.conf;
  include /etc/nginx/sites-enabled/*;
}

Main structure.

CLI Commands
nginx -t          # test config
nginx -s reload   # reload
nginx -s stop     # stop
nginx -s quit     # graceful stop
systemctl restart nginx

Manage the service.

Serve Static Files
server {
  listen 80;
  server_name example.com;
  root /var/www/html;
  index index.html;

  location / {
    try_files $uri $uri/ =404;
  }
}

File server.

Logs
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log warn;

# Per server block:
access_log /var/log/nginx/site.log main;

# Disable:
access_log off;

Configure logging.

Server Blocks


4 cards
Basic Virtual Host
# /etc/nginx/sites-available/site
server {
  listen 80;
  server_name app.example.com;
  root /var/www/app/public;
  index index.php index.html;
}

# Enable:
# ln -s sites-available/site sites-enabled/

Create a virtual host.

Multiple Domains
server {
  server_name example.com www.example.com;
}

server {
  server_name api.example.com;
  # different config
}

# Wildcard:
server_name *.example.com;

Several domains.

SPA (React/Vue/Angular)
server {
  root /var/www/spa/dist;
  index index.html;

  location / {
    try_files $uri $uri/ /index.html;
  }
}

Single Page Applications.

Laravel / PHP-FPM
location ~ \.php$ {
  fastcgi_pass unix:/run/php-fpm.sock;
  fastcgi_param SCRIPT_FILENAME
    $realpath_root$fastcgi_script_name;
  include fastcgi_params;
}

location / {
  try_files $uri $uri/ /index.php?$query_string;
}

Config for PHP/Laravel.

Reverse Proxy


4 cards
Basic Proxy
location / {
  proxy_pass http://127.0.0.1:3000;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP
    $remote_addr;
  proxy_set_header X-Forwarded-For
    $proxy_add_x_forwarded_for;
}

Proxy for a Node/Python app.

WebSocket Proxy
location /ws {
  proxy_pass http://127.0.0.1:8080;
  proxy_http_version 1.1;
  proxy_set_header Upgrade
    $http_upgrade;
  proxy_set_header Connection
    "upgrade";
}

WebSocket support.

Load Balancing
upstream backend {
  least_conn;
  server 10.0.0.1:8080 weight=3;
  server 10.0.0.2:8080;
  server 10.0.0.3:8080 backup;
}

location / {
  proxy_pass http://backend;
}

Distribute traffic.

Proxy with Path
# /api/ → app:3000/
location /api/ {
  proxy_pass http://127.0.0.1:3000/;
}

# /app/ → app:8080/app/
location /app/ {
  proxy_pass http://127.0.0.1:8080;
}

Map paths.

SSL / HTTPS


4 cards
Basic HTTPS
server {
  listen 443 ssl;
  server_name example.com;

  ssl_certificate /etc/ssl/cert.pem;
  ssl_certificate_key /etc/ssl/key.pem;
  ssl_protocols TLSv1.2 TLSv1.3;
}

Enable SSL/TLS.

Redirect HTTP → HTTPS
server {
  listen 80;
  server_name example.com;
  return 301 https://$host$request_uri;
}

server {
  listen 443 ssl;
  # ... main config
}

Force HTTPS.

Certbot (Let's Encrypt)
certbot --nginx -d example.com
certbot --nginx -d example.com \
  -d www.example.com

# Renew automatically:
certbot renew --dry-run

# Cron: 0 3 * * * certbot renew

Free certificates.

Security Headers
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options
  nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Strict-Transport-Security
  "max-age=31536000" always;
add_header Content-Security-Policy
  "default-src 'self'";

Protection headers.

Performance


4 cards
Gzip Compression
gzip on;
gzip_types text/plain text/css
  application/json application/javascript
  text/xml application/xml;
gzip_min_length 1000;
gzip_vary on;
gzip_comp_level 5;

Compress responses.

Static File Caching
location ~* \.(jpg|png|gif|css|js|woff2)$ {
  expires 30d;
  add_header Cache-Control
    "public, immutable";
}

location ~* \.html$ {
  expires -1;
}

Browser caching.

Proxy Cache
proxy_cache_path /var/cache/nginx
  levels=1:2 keys_zone=app:10m
  max_size=1g inactive=60m;

location / {
  proxy_cache app;
  proxy_cache_valid 200 10m;
  proxy_cache_valid 404 1m;
}

Server-side caching.

Optimizations
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
client_max_body_size 50M;
open_file_cache max=10000 inactive=30s;

Performance tuning.

Advanced


4 cards
Rewrite and Redirect
rewrite ^/old/(.*)$ /new/$1 permanent;
rewrite ^/blog/(\d+)$ /post?id=$1 last;

# Conditional redirect:
if ($http_user_agent ~* "bot") {
  return 403;
}

Rewrite URLs.

Rate Limiting
# In http {}:
limit_req_zone $binary_remote_addr
  zone=api:10m rate=10r/s;

# In the location:
location /api/ {
  limit_req zone=api burst=20 nodelay;
}

Limit requests.

Block Access
location ~ /\.ht {
  deny all;
}

location /admin {
  allow 192.168.1.0/24;
  deny all;
}

# Block user-agent:
if ($http_user_agent ~* "curl|wget") {
  return 403;
}

Restrict access.

Debug and Status
# Status page:
location /nginx_status {
  stub_status on;
  allow 127.0.0.1;
  deny all;
}

# Debug: error_log with debug level
error_log /var/log/nginx/debug.log debug;

# View active config:
nginx -T

Monitor and debug.