DevTools

Cheatsheet Nginx

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

Volver a los lenguajes
Nginx
24 tarjetas encontradas
Categorías:
Versiones:

Configuração Básica


4 cards
Estructura del config
# /etc/nginx/nginx.conf
worker_processes auto;

events {
  worker_connections 1024;
}

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

Estructura principal.

Comandos CLI
nginx -t          # probar config
nginx -s reload   # recargar
nginx -s stop     # parar
nginx -s quit     # graceful stop
systemctl restart nginx

Gestionar el servicio.

Servir estáticos
server {
  listen 80;
  server_name ejemplo.com;
  root /var/www/html;
  index index.html;

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

Servidor de archivos.

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

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

# Desactivar:
access_log off;

Configurar logging.

Server Blocks


4 cards
Virtual host básico
# /etc/nginx/sites-available/site
server {
  listen 80;
  server_name app.ejemplo.com;
  root /var/www/app/public;
  index index.php index.html;
}

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

Crear virtual host.

Múltiples dominios
server {
  server_name ejemplo.com www.ejemplo.com;
}

server {
  server_name api.ejemplo.com;
  # config diferente
}

# Wildcard:
server_name *.ejemplo.com;

Varios dominios.

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 para PHP/Laravel.

Reverse Proxy


4 cards
Proxy básico
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 para app Node/Python.

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";
}

Soporte para WebSockets.

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;
}

Distribuir tráfico.

Proxy con 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;
}

Mapear rutas.

SSL / HTTPS


4 cards
HTTPS básico
server {
  listen 443 ssl;
  server_name ejemplo.com;

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

Activar SSL/TLS.

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

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

Forzar HTTPS.

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

# Renovar automáticamente:
certbot renew --dry-run

# Cron: 0 3 * * * certbot renew

Certificados gratuitos.

Headers de seguridad
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'";

Headers de protección.

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;

Comprimir respuestas.

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

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

Cache en el navegador.

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;
}

Cache en el servidor.

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

Tuning de rendimiento.

Avançado


4 cards
Rewrite y redirect
rewrite ^/antiguo/(.*)$ /nuevo/$1 permanent;
rewrite ^/blog/(\d+)$ /post?id=$1 last;

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

Reescribir URLs.

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

# En el location:
location /api/ {
  limit_req zone=api burst=20 nodelay;
}

Limitar peticiones.

Bloquear accesos
location ~ /\.ht {
  deny all;
}

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

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

Restringir acceso.

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

# Debug: error_log con nivel debug
error_log /var/log/nginx/debug.log debug;

# Ver config activa:
nginx -T

Monitorizar y depurar.