Cheatsheet Nginx
Servidor web, reverse proxy e balanceador de carga de alta performance
Nginx
24
cards encontrados
Categorias:
Versões:
Configuração Básica
Estrutura do config
# /etc/nginx/nginx.conf
worker_processes auto;
events {
worker_connections 1024;
}
http {
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
Estrutura principal.
Comandos CLI
nginx -t # testar config
nginx -s reload # recarregar
nginx -s stop # parar
nginx -s quit # graceful stop
systemctl restart nginx
Gerir o serviço.
Servir estáticos
server {
listen 80;
server_name exemplo.com;
root /var/www/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}Servidor de ficheiros.
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;
# Desativar:
access_log off;
Configurar logging.
Server Blocks
Virtual host básico
# /etc/nginx/sites-available/site
server {
listen 80;
server_name app.exemplo.com;
root /var/www/app/public;
index index.php index.html;
}
# Ativar:
# ln -s sites-available/site sites-enabled/
Criar virtual host.
Múltiplos domínios
server {
server_name exemplo.com www.exemplo.com;
}
server {
server_name api.exemplo.com;
# config diferente
}
# Wildcard:
server_name *.exemplo.com;Vários domínios.
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
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";
}Suporte a 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áfego.
Proxy com 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 caminhos.
SSL / HTTPS
HTTPS básico
server {
listen 443 ssl;
server_name exemplo.com;
ssl_certificate /etc/ssl/cert.pem;
ssl_certificate_key /etc/ssl/key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
}Ativar SSL/TLS.
Redirect HTTP → HTTPS
server {
listen 80;
server_name exemplo.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
# ... config principal
}Forçar HTTPS.
Certbot (Let's Encrypt)
certbot --nginx -d exemplo.com
certbot --nginx -d exemplo.com \
-d www.exemplo.com
# Renovar automaticamente:
certbot renew --dry-run
# Cron: 0 3 * * * certbot renew
Certificados gratuitos.
Headers de segurança
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 proteção.
Performance
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 respostas.
Cache de estáticos
location ~* \.(jpg|png|gif|css|js|woff2)$ {
expires 30d;
add_header Cache-Control
"public, immutable";
}
location ~* \.html$ {
expires -1;
}Cache no browser.
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 no servidor.
Otimizações
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 performance.
Avançado
Rewrite e redirect
rewrite ^/antigo/(.*)$ /novo/$1 permanent;
rewrite ^/blog/(\d+)$ /post?id=$1 last;
# Redirect condicional:
if ($http_user_agent ~* "bot") {
return 403;
}
Reescrever URLs.
Rate limiting
# No http {}:
limit_req_zone $binary_remote_addr
zone=api:10m rate=10r/s;
# No location:
location /api/ {
limit_req zone=api burst=20 nodelay;
}Limitar pedidos.
Bloquear acessos
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 acesso.
Debug e status
# Status page:
location /nginx_status {
stub_status on;
allow 127.0.0.1;
deny all;
}
# Debug: error_log com nível debug
error_log /var/log/nginx/debug.log debug;
# Ver config ativa:
nginx -T
Monitorizar e depurar.