Nginx is a high-performance web server, reverse proxy and load balancer widely used to serve websites and modern applications.
Service Management
Action Command Start nginx sudo systemctl start nginxStop nginx sudo systemctl stop nginxRestart nginx sudo systemctl restart nginxReload configuration sudo systemctl reload nginxService status sudo systemctl status nginxEnable at boot sudo systemctl enable nginxTest configuration sudo nginx -tNginx version nginx -v
Configuration
File/Directory Description /etc/nginx/nginx.confMain configuration /etc/nginx/sites-available/Available sites /etc/nginx/sites-enabled/Active sites (symbolic links) /etc/nginx/conf.d/Additional configurations /var/log/nginx/Access and error logs /var/www/html/Default web directory /usr/share/nginx/html/Nginx default pages
Site Management
Action Command Create a site sudo nano /etc/nginx/sites-available/mysiteEnable a site sudo ln -s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/Disable a site sudo rm /etc/nginx/sites-enabled/mysiteList active sites ls -la /etc/nginx/sites-enabled/Verify configuration sudo nginx -t && sudo systemctl reload nginxDelete a site sudo rm /etc/nginx/sites-available/mysite
Basic Directives
Directive Description Example listenListening port listen 80;server_nameServer name server_name example.com;rootRoot directory root /var/www/html;indexIndex files index index.html index.php;error_pageCustom error pages error_page 404 /404.html;
Basic Site Configuration
Simple Static Site
server {
listen 80 ;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html index.htm;
location / {
try_files $uri $uri/ =404 ;
}
}
Site with PHP (FastCGI)
server {
listen 80 ;
server_name example.com;
root /var/www/example.com;
index index.php index.html;
location / {
try_files $uri $uri/ =404 ;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
Proxy to Application
server {
listen 80 ;
server_name app.example.com;
location / {
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;
}
}
SSL/HTTPS Configuration
Action Command Generate self-signed certificate sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/nginx.key -out /etc/ssl/certs/nginx.crtInstall Certbot sudo apt install certbot python3-certbot-nginxGet Let’s Encrypt certificate sudo certbot --nginx -d example.comRenew certificates sudo certbot renewAuto-renewal sudo crontab -e -> 0 0 * * * certbot renew --quiet
HTTPS Configuration
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on ;
root /var/www/example.com;
index index.html;
}
# HTTP to HTTPS redirect
server {
listen 80 ;
server_name example.com;
return 301 https://$server_name$request_uri;
}
Logs and Monitoring
Action Command Real-time access logs sudo tail -f /var/log/nginx/access.logReal-time error logs sudo tail -f /var/log/nginx/error.logSearch in logs sudo grep "404" /var/log/nginx/access.logStatus code statistics `awk ‘{print $9}’ /var/log/nginx/access.log Top visitor IPs `awk ‘{print $1}’ /var/log/nginx/access.log Most visited pages `awk ‘{print $7}’ /var/log/nginx/access.log
General Configuration (/etc/nginx/nginx.conf)
# Processes and connections
worker_processes auto;
worker_connections 1024 ;
# File optimization
sendfile on ;
tcp_nopush on ;
tcp_nodelay on ;
# Timeout management
keepalive_timeout 65 ;
client_max_body_size 64M ;
# Gzip compression
gzip on ;
gzip_vary on ;
gzip_min_length 1024 ;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
Static Cache (speed up images/CSS/JS files)
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 1y; # Cache 1 year
add_header Cache-Control "public" ; # Public cache
}
Load Balancing
Upstream Configuration
upstream backend {
server 192.168.1.10:8080 weight = 3 ;
server 192.168.1.11:8080 weight = 2 ;
server 192.168.1.12:8080 backup;
}
server {
listen 80 ;
server_name app.example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
Load Balancing Methods
# Round robin (default)
upstream backend {
server srv1.example.com;
server srv2.example.com;
}
# Least connections
upstream backend {
least_conn ;
server srv1.example.com;
server srv2.example.com;
}
# IP Hash (sticky session)
upstream backend {
ip_hash ;
server srv1.example.com;
server srv2.example.com;
}
Security
Protection Configuration Hide nginx version server_tokens off;Security headers add_header X-Content-Type-Options nosniff;XSS protection add_header X-XSS-Protection "1; mode=block";HSTS add_header Strict-Transport-Security "max-age=31536000";Block IPs deny 192.168.1.100;Allow only allow 192.168.1.0/24; deny all;
Secure Configuration
# 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 "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: ws: wss: data: blob: 'unsafe-inline'; frame-ancestors 'self';" always;
# Hide sensitive files
location ~ /\. {
deny all ;
}
location ~* \.(conf|ini|sql|sh|py|yml|yaml)$ {
deny all ;
}
Common Troubleshooting
Problem Solution Configuration error sudo nginx -t then fix the errors403 Forbidden Check file permissions 404 Not Found Check root and index in config Connection refused Check that nginx is listening on the right port Proxy error Check that the backend application is running Empty logs Check logs directory permissions