Instalasi
Instalasi per OS
Ubuntu / Debiansudo apt install nginx
RHEL / CentOSsudo dnf install nginx
macOSbrew install nginx
Alpineapk add nginx
Dockerdocker run -p 80:80 nginx
Manajemen Layanan
sudo systemctl start nginxMulai Nginx
sudo systemctl stop nginxHentikan Nginx
sudo systemctl reload nginxMuat ulang konfigurasi (tanpa downtime)
sudo systemctl enable nginxAktifkan saat booting
nginx -tUji sintaks konfigurasi
nginx -TUji dan tampilkan konfigurasi lengkap
nginx -s reloadKirim sinyal reload ke proses yang berjalan
Konfigurasi Dasar
Lokasi File
/etc/nginx/nginx.confFile konfigurasi utama
/etc/nginx/conf.d/Konfigurasi site tambahan (*.conf)
/etc/nginx/sites-available/Konfigurasi site tersedia (Debian)
/etc/nginx/sites-enabled/Symlink ke konfigurasi aktif
/var/log/nginx/Log akses dan error
/var/www/html/Document root default
Konfigurasi Minimal
server { listen 80; server_name example.com; root /var/www/mysite; index index.html; }
Struktur Konfigurasi
http { }Pengaturan server HTTP (level teratas)
server { }Definisi virtual host
location { }Blok pencocokan URI
upstream { }Grup server backend
events { }Pengaturan penanganan koneksi
Server Block
Virtual Host Berbasis Nama
server { listen 80; server_name site-a.com; root /var/www/site-a; } server { listen 80; server_name site-b.com; root /var/www/site-b; }
Default & Catch-All
server { listen 80 default_server; server_name _; return 444; # putus koneksi }
Redirect ke HTTPS
server { listen 80; server_name example.com; return 301 https://$host$request_uri; }
Location Block
Prioritas Pencocokan (tinggi ke rendah)
= /pathPencocokan tepat (prioritas tertinggi)
^~ /pathPencocokan prefix, lewati regex
~ regexRegex case-sensitive
~* regexRegex case-insensitive
/pathPencocokan prefix (prioritas terendah)
Contoh Location
location = / { # hanya root tepat } location /api/ { proxy_pass http://backend; } location ~* \.(jpg|png|gif)$ { expires 30d; }
try_files
location / { try_files $uri $uri/ /index.html; }

Coba file, direktori, lalu fallback -- penting untuk SPA

Reverse Proxy
Proxy Dasar
location /api/ { proxy_pass http://localhost: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_set_header X-Forwarded-Proto $scheme; }
Proxy WebSocket
location /ws/ { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }
Direktif Proxy
proxy_passURL backend
proxy_set_headerTeruskan header kustom ke backend
proxy_read_timeoutTimeout respons backend (default 60s)
proxy_buffering offNonaktifkan buffering respons
proxy_redirectTulis ulang header Location dari backend
SSL / TLS
Server HTTPS
server { listen 443 ssl; server_name example.com; ssl_certificate /etc/ssl/certs/example.crt; ssl_certificate_key /etc/ssl/private/example.key; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; }
Let's Encrypt dengan Certbot
sudo certbot --nginx -d example.com sudo certbot renew --dry-run
Best Practice SSL
ssl_protocols TLSv1.2 TLSv1.3Nonaktifkan versi TLS lama
ssl_prefer_server_ciphers onServer memilih cipher
ssl_session_cache shared:SSL:10mReuse sesi untuk performa
add_header Strict-Transport-SecurityHeader HSTS
ssl_stapling onOCSP stapling untuk handshake lebih cepat
Load Balancing
Blok Upstream
upstream backend { server 10.0.0.1:3000; server 10.0.0.2:3000; server 10.0.0.3:3000; } server { location / { proxy_pass http://backend; } }
Metode Load Balancing
(default)Round-robin
least_connKoneksi aktif paling sedikit
ip_hashSesi sticky berdasarkan IP client
hash $request_uriHash konsisten berdasarkan URI
Opsi Server
weight=3Kirim 3x lebih banyak traffic
max_fails=3Kegagalan sebelum ditandai mati
fail_timeout=30sWaktu menandai server sebagai mati
backupGunakan hanya jika server lain mati
downTandai server sebagai offline permanen
File Statis & Caching
Sajikan File Statis
location /static/ { alias /var/www/assets/; expires 30d; add_header Cache-Control "public, immutable"; }
Kompresi Gzip
gzip on; gzip_types text/plain text/css application/json application/javascript; gzip_min_length 1000; gzip_comp_level 5;
Direktif Caching
expires 30dSet header Expires dan Cache-Control max-age
expires offNonaktifkan header expires
etag onAktifkan header ETag (default)
sendfile onPenyajian file efisien via kernel
tcp_nopush onOptimalkan pengiriman paket
Logging
Konfigurasi Log
access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log warn; # Format log kustom log_format main '$remote_addr - $status ' '"$request" $body_bytes_sent'; access_log /var/log/nginx/access.log main;
Level Log Error
debugVerbose (perlu --with-debug)
infoInformasional
noticeNormal tapi perlu diperhatikan
warnPeringatan
errorError (default)
critMasalah kritis
Logging Kondisional
map $status $loggable { ~^[23] 0; default 1; } access_log /var/log/nginx/access.log combined if=$loggable;

Lewati logging respons 2xx/3xx untuk mengurangi volume log

Keamanan
Rate Limiting
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s; location /api/ { limit_req zone=api burst=20 nodelay; }
Kontrol Akses
location /admin/ { allow 192.168.1.0/24; deny all; }
Header Keamanan
X-Frame-Options DENYCegah clickjacking
X-Content-Type-Options nosniffCegah MIME sniffing
X-XSS-Protection "1; mode=block"Filter XSS (browser lama)
Content-Security-PolicyKontrol sumber pemuatan resource
Referrer-Policy no-referrerKontrol informasi referrer
Pola Umum
SPA (Single-Page App)
location / { root /var/www/app; try_files $uri $uri/ /index.html; }
Header CORS
location /api/ { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"; if ($request_method = OPTIONS) { return 204; } proxy_pass http://backend; }
Variabel Berguna
$hostHeader Host request
$uriURI saat ini (ternormalisasi)
$request_uriURI asli dengan query string
$remote_addrAlamat IP client
$schemehttp atau https
$argsParameter query string
$statusKode status respons