skip to content

Search

Syspirit
EN

Nginx

Nginx web server - configuration, virtual hosts, SSL and optimization!

Nginx is a high-performance web server, reverse proxy and load balancer widely used to serve websites and modern applications.

Service Management

ActionCommand
Start nginxsudo systemctl start nginx
Stop nginxsudo systemctl stop nginx
Restart nginxsudo systemctl restart nginx
Reload configurationsudo systemctl reload nginx
Service statussudo systemctl status nginx
Enable at bootsudo systemctl enable nginx
Test configurationsudo nginx -t
Nginx versionnginx -v

Configuration

File/DirectoryDescription
/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

ActionCommand
Create a sitesudo nano /etc/nginx/sites-available/mysite
Enable a sitesudo ln -s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/
Disable a sitesudo rm /etc/nginx/sites-enabled/mysite
List active sitesls -la /etc/nginx/sites-enabled/
Verify configurationsudo nginx -t && sudo systemctl reload nginx
Delete a sitesudo rm /etc/nginx/sites-available/mysite

Basic Directives

DirectiveDescriptionExample
listenListening portlisten 80;
server_nameServer nameserver_name example.com;
rootRoot directoryroot /var/www/html;
indexIndex filesindex index.html index.php;
error_pageCustom error pageserror_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

ActionCommand
Generate self-signed certificatesudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/nginx.key -out /etc/ssl/certs/nginx.crt
Install Certbotsudo apt install certbot python3-certbot-nginx
Get Let’s Encrypt certificatesudo certbot --nginx -d example.com
Renew certificatessudo certbot renew
Auto-renewalsudo 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

ActionCommand
Real-time access logssudo tail -f /var/log/nginx/access.log
Real-time error logssudo tail -f /var/log/nginx/error.log
Search in logssudo grep "404" /var/log/nginx/access.log
Status 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

Optimization and Performance

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

ProtectionConfiguration
Hide nginx versionserver_tokens off;
Security headersadd_header X-Content-Type-Options nosniff;
XSS protectionadd_header X-XSS-Protection "1; mode=block";
HSTSadd_header Strict-Transport-Security "max-age=31536000";
Block IPsdeny 192.168.1.100;
Allow onlyallow 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

ProblemSolution
Configuration errorsudo nginx -t then fix the errors
403 ForbiddenCheck file permissions
404 Not FoundCheck root and index in config
Connection refusedCheck that nginx is listening on the right port
Proxy errorCheck that the backend application is running
Empty logsCheck logs directory permissions