Nginx adalah web server yang sangat populer karena performa tinggi, konsumsi resource yang rendah, dan kemampuan handle concurrent connections yang excellent. Artikel ini membahas instalasi dan konfigurasi lengkap Nginx di Ubuntu 22.04.
1. Instalasi Nginx
Install dari Repository Ubuntu
# Update package list
sudo apt update
Install Nginx
sudo apt install -y nginx
Verifikasi instalasi
nginx -v
Cek status service
sudo systemctl status nginx
Enable dan Start Nginx
# Enable start on boot
sudo systemctl enable nginx
Start Nginx
sudo systemctl start nginx
Restart Nginx
sudo systemctl restart nginx
Reload configuration (graceful)
sudo systemctl reload nginx
2. Verifikasi Instalasi
Cek Nginx Running
# Test konfigurasi
sudo nginx -t
Cek ports yang listening
sudo ss -tlnp | grep :80
sudo ss -tlnp | grep :443
Cek dengan curl
curl -I
http://localhost
Atau buka browser dan akses
http://your-server-ip
Seharusnya muncul "Welcome to nginx!"
Firewall Configuration
# Allow Nginx Full (HTTP dan HTTPS)
sudo ufw allow 'Nginx Full'
Atau allow manual
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
Cek status
sudo ufw status
3. Struktur Konfigurasi Nginx
Direktori Penting
/etc/nginx/
βββ nginx.conf # Konfigurasi utama
βββ sites-available/ # Virtual hosts available
βββ sites-enabled/ # Virtual hosts enabled (symlink)
βββ snippets/ # Configuration snippets
βββ modules-available/ # Modules available
βββ modules-enabled/ # Modules enabled
File Konfigurasi Utama
Edit /etc/nginx/nginx.conf:
user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf;events { worker_connections 768;
multi_accept on;
}
http {
Basic Settings
sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; server_tokens off; # MIME Types include /etc/nginx/mime.types; default_type application/octet-stream; # SSL Settings ssl_protocols TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers on; # Logging access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; # Gzip Settings gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_types text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml; # Virtual Host Configs include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*;}
4. Virtual Hosts Configuration
Setup Direktori Website
# Buat direktori untuk website sudo mkdir -p /var/www/example.com/html sudo mkdir -p /var/www/example.com/logsBuat index.html test
sudo tee /var/www/example.com/html/index.html <<EOF <!DOCTYPE html> <html> <head> <title>Welcome to Example.com</title> </head> <body> <h1>Success! Nginx server block is working!</h1> </body> </html> EOF
Set ownership
sudo chown -R www-data:www-data /var/www/example.com
Set permissions
sudo chmod -R 755 /var/www
Buat Server Block
Buat file
/etc/nginx/sites-available/example.com:server { listen 80; listen [::]:80;server_name example.com www.example.com; root /var/www/example.com/html; index index.html index.htm index.php index.nginx-debian.html; access_log /var/www/example.com/logs/access.log; error_log /var/www/example.com/logs/error.log; location / { try_files $uri $uri/ =404; } # Security: Hide nginx version server_tokens off; # Deny access to hidden files location ~ /\. { deny all; } # PHP handling (jika menggunakan PHP-FPM) location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; }}
Enable Server Block
# Create symlink ke sites-enabled sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/Remove default site (optional)
sudo rm /etc/nginx/sites-enabled/default
Test konfigurasi
sudo nginx -t
Reload Nginx
sudo systemctl reload nginx
5. SSL/HTTPS dengan Let’s Encrypt
Install Certbot
# Install Certbot dan plugin Nginx sudo apt install -y certbot python3-certbot-nginxDapatkan Certificate
# Automatic configuration sudo certbot --nginx -d example.com -d www.example.comAtau dengan email dan agree TOS
sudo certbot --nginx --non-interactive --agree-tos --email [email protected] -d example.com -d www.example.com
Auto-Renewal
# Test auto-renewal sudo certbot renew --dry-runSetup cron (biasanya sudah otomatis)
sudo systemctl status certbot.timer
6. Optimasi Performa Nginx
Worker Processes dan Connections
Edit
/etc/nginx/nginx.conf:# Sesuaikan dengan jumlah CPU cores worker_processes auto; worker_rlimit_nofile 65535;events { worker_connections 4096; use epoll; multi_accept on; }
File Cache dan Buffers
http { # File cache open_file_cache max=1000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2; open_file_cache_errors on;# Buffers client_body_buffer_size 128k; client_max_body_size 50m; client_header_buffer_size 1k; large_client_header_buffers 4 4k; # Output buffers output_buffers 1 32k; postpone_output 1460;}
Enable Gzip Compression
gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_min_length 256; gzip_types application/atom+xml application/javascript application/json application/ld+json application/manifest+json application/rss+xml application/vnd.geo+json application/vnd.ms-fontobject application/x-font-ttf application/x-web-app-manifest+json application/xhtml+xml application/xml font/opentype image/bmp image/svg+xml image/x-icon text/cache-manifest text/css text/plain text/vcard text/vnd.rim.location.xloc text/vtt text/x-component text/x-cross-domain-policy;Enable Brotli Compression (Optional)
# Install Brotli module (dari source atau repository third-party) # Konfigurasi: brotli on; brotli_comp_level 6; brotli_types text/plain text/css text/xml application/json application/javascript application/rss+xml text/javascript application/x-javascript;Browser Caching
Tambahkan di server block:
# Static files caching location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg)$ { expires 1y; add_header Cache-Control "public, immutable"; }HTML caching
location ~* .html$ { expires 1h; add_header Cache-Control "public, must-revalidate"; }
7. Load Balancing
Basic Load Balancer
upstream backend { server 192.168.1.10:8080; server 192.168.1.11:8080; server 192.168.1.12:8080; }server { listen 80; server_name api.example.com;
location / { proxy_pass http://backend; 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; }}
Load Balancing Methods
upstream backend { # Least connections (default: round robin) least_conn;# IP Hash (sticky sessions) # ip_hash; # Weighted # server 192.168.1.10:8080 weight=5; # server 192.168.1.11:8080 weight=3; server 192.168.1.10:8080; server 192.168.1.11:8080 backup; # Backup server server 192.168.1.12:8080 down; # Maintenance}
8. Reverse Proxy
Reverse Proxy ke Application Server
server { listen 80; server_name app.example.com;location / { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; 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_cache_bypass $http_upgrade; # Timeout settings proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s; }}
WebSocket Support
location /ws { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; 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; }9. Security Hardening
Rate Limiting
# Edit nginx.conf limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s; limit_conn_zone $binary_remote_addr zone=addr:10m;server { location / { limit_req zone=one burst=5 nodelay; limit_conn addr 10; } }Block Bad Bots
# Di http block map $http_user_agent $limit_bots { default 0; ~*(google|bing|yahoo|msnbot|yandex|baiduspider|facebook) 0; ~*(bot|crawler|spider|scraper|scan|curl|wget) 1; }server { if ($limit_bots) { return 403; } }
Security Headers
add_header X-Frame-Options "SAMEORIGIN" always; add_header X-Content-Type-Options "nosniff" always; add_header X-XSS-Protection "1; mode=block" always; add_header Referrer-Policy "strict-origin-when-cross-origin" always; add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;Deny Access ke Sensitive Files
location ~ /\.(?!well-known).* { deny all; }location ~* .(git|svn|htaccess|env|ini|log|sql)$ { deny all; }
location ~ /(composer.(json|lock)|package.json|gulpfile.js)$ { deny all; }
10. Monitoring dan Logging
Custom Log Format
log_format custom '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' '$request_time $upstream_response_time';access_log /var/log/nginx/access.log custom;
Monitoring dengan stub_status
server { listen 80; server_name localhost;location /nginx_status { stub_status on; allow 127.0.0.1; deny all; }}
Akses dengan:
curl http://localhost/nginx_status11. Troubleshooting
1. Test Konfigurasi
sudo nginx -t2. Check Error Logs
sudo tail -f /var/log/nginx/error.log3. Common Errors
403 Forbidden:
# Check permissions ls -la /var/www/ sudo chown -R www-data:www-data /var/www/ sudo chmod -R 755 /var/www/502 Bad Gateway (PHP-FPM):
# Check PHP-FPM status sudo systemctl status php8.1-fpmCheck socket exists
ls -la /var/run/php/
Fix permission
sudo usermod -a -G www-data nginx
Too Many Open Files:
# Increase limits sudo nano /etc/security/limits.confTambahkan:
www-data soft nofile 65535 www-data hard nofile 65535
4. Performance Testing
# Install Apache Bench sudo apt install apache2-utilsTest
ab -n 10000 -c 100 http://example.com/
Atau dengan wrk
wrk -t12 -c400 -d30s http://example.com/
Kesimpulan
Nginx adalah web server yang powerful dengan konfigurasi fleksibel. Dengan setup di atas, Anda mendapatkan:
- Web server yang optimized untuk static content
- Reverse proxy untuk application servers
- Load balancer untuk high availability
- SSL/HTTPS dengan Let’s Encrypt
- Security hardening dengan rate limiting dan security headers
- Caching dan compression untuk performa maksimal
Nginx sangat cocok untuk production environment dengan traffic tinggi.
Ditulis oleh
Hendra Wijaya