REFERENSI CEPAT NGINX
Server block, proxy, SSL, load balancing, logging
Instalasi
Instalasi per OS
| Ubuntu / Debian | sudo apt install nginx |
| RHEL / CentOS | sudo dnf install nginx |
| macOS | brew install nginx |
| Alpine | apk add nginx |
| Docker | docker run -p 80:80 nginx |
Manajemen Layanan
| sudo systemctl start nginx | Mulai Nginx |
| sudo systemctl stop nginx | Hentikan Nginx |
| sudo systemctl reload nginx | Muat ulang konfigurasi (tanpa downtime) |
| sudo systemctl enable nginx | Aktifkan saat booting |
| nginx -t | Uji sintaks konfigurasi |
| nginx -T | Uji dan tampilkan konfigurasi lengkap |
| nginx -s reload | Kirim sinyal reload ke proses yang berjalan |
Konfigurasi Dasar
Lokasi File
| /etc/nginx/nginx.conf | File 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)
| = /path | Pencocokan tepat (prioritas tertinggi) |
| ^~ /path | Pencocokan prefix, lewati regex |
| ~ regex | Regex case-sensitive |
| ~* regex | Regex case-insensitive |
| /path | Pencocokan 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_pass | URL backend |
| proxy_set_header | Teruskan header kustom ke backend |
| proxy_read_timeout | Timeout respons backend (default 60s) |
| proxy_buffering off | Nonaktifkan buffering respons |
| proxy_redirect | Tulis 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.3 | Nonaktifkan versi TLS lama |
| ssl_prefer_server_ciphers on | Server memilih cipher |
| ssl_session_cache shared:SSL:10m | Reuse sesi untuk performa |
| add_header Strict-Transport-Security | Header HSTS |
| ssl_stapling on | OCSP 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_conn | Koneksi aktif paling sedikit |
| ip_hash | Sesi sticky berdasarkan IP client |
| hash $request_uri | Hash konsisten berdasarkan URI |
Opsi Server
| weight=3 | Kirim 3x lebih banyak traffic |
| max_fails=3 | Kegagalan sebelum ditandai mati |
| fail_timeout=30s | Waktu menandai server sebagai mati |
| backup | Gunakan hanya jika server lain mati |
| down | Tandai 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 30d | Set header Expires dan Cache-Control max-age |
| expires off | Nonaktifkan header expires |
| etag on | Aktifkan header ETag (default) |
| sendfile on | Penyajian file efisien via kernel |
| tcp_nopush on | Optimalkan 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
| debug | Verbose (perlu --with-debug) |
| info | Informasional |
| notice | Normal tapi perlu diperhatikan |
| warn | Peringatan |
| error | Error (default) |
| crit | Masalah 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 DENY | Cegah clickjacking |
| X-Content-Type-Options nosniff | Cegah MIME sniffing |
| X-XSS-Protection "1; mode=block" | Filter XSS (browser lama) |
| Content-Security-Policy | Kontrol sumber pemuatan resource |
| Referrer-Policy no-referrer | Kontrol 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
| $host | Header Host request |
| $uri | URI saat ini (ternormalisasi) |
| $request_uri | URI asli dengan query string |
| $remote_addr | Alamat IP client |
| $scheme | http atau https |
| $args | Parameter query string |
| $status | Kode status respons |