Nginx Gebruikershandleiding

Basisbewerkingen

Nginx starten

# Start Nginx
nginx

# Or using systemctl (for systemd)
systemctl start nginx

Nginx stoppen

# Fast shutdown (terminate immediately)
nginx -s stop

# Graceful shutdown (wait for requests to complete)
nginx -s quit

De configuratie herladen

# Reload configuration file
nginx -s reload

De logboeken heropenen

# Reopen log files
nginx -s reopen

De configuratie controleren

# Test configuration syntax
nginx -t

# View full configuration
nginx -T

Structuur van het configuratiebestand

Structuur van de hoofdconfiguratie

nginx.conf
├── main (global block)
│   ├── user
│   ├── worker_processes
│   ├── error_log
│   └── pid
│
├── events (events block)
│   └── worker_connections
│
└── http (http block)
    ├── include
    ├── default_type
    ├── log_format
    ├── access_log
    ├── sendfile
    ├── keepalive_timeout
    ├── gzip
    │
    └── server (server block)
        ├── listen
        ├── server_name
        ├── location
        │   ├── root
        │   ├── index
        │   └── proxy_pass
        │
        └── error_page

Gangbare directives

Hoofdblok

# User running Nginx
user nginx;

# Number of worker processes (auto detects CPU cores)
worker_processes auto;

# Error log path
error_log /var/log/nginx/error.log warn;

# PID file path
pid /var/run/nginx.pid;

Events-blok

events {
    # Maximum connections per worker
    worker_connections 1024;
    
    # Use epoll model (Linux)
    use epool;
    
    # Accept multiple connections simultaneously
    multi_accept on;
}

HTTP-blok

http {
    # Include MIME types
    include /etc/nginx/mime.types;
    
    # Default file type
    default_type application/octet-stream;
    
    # Access log
    access_log /var/log/nginx/access.log;
    
    # Send file
    sendfile on;
    
    # TCP_NOPUSH and TCP_NODELAY
    tcp_nopush on;
    tcp_nodelay on;
    
    # Keep-alive timeout
    keepalive_timeout 65;
    
    # Enable gzip compression
    gzip on;
}

Statische bestanden serveren

Basisconfiguratie

server {
    listen 80;
    server_name example.com www.example.com;
    
    # Root directory
    root /var/www/html;
    
    # Default index files
    index index.html index.htm;
    
    location / {
        try_files $uri $uri/ =404;
    }
    
    # Access logs
    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;
}

Directory listing

location / {
    # Enable directory listing
    autoindex on;
    
    # Show file sizes
    autoindex_exact_size on;
    
    # Show local time
    autoindex_localtime on;
}

Caching van statische bronnen

location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|svg)$ {
    expires 30d;
    add_header Cache-Control "public, no-transform";
}

Reverse proxy

Basis reverse proxy

server {
    listen 80;
    server_name example.com;
    
    location / {
        proxy_pass http://backend_server;
        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;
    }
}

Reverse proxy met caching

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=100m inactive=60m use_temp_path=off;

server {
    listen 80;
    server_name example.com;
    
    location / {
        proxy_cache my_cache;
        proxy_cache_valid 200 60m;
        proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
        proxy_cache_lock on;
        
        proxy_pass http://backend_server;
        proxy_set_header Host $host;
    }
}

WebSocket-proxy

location /ws/ {
    proxy_pass http://backend_server;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_read_timeout 86400;
}

Load balancing

Round-robin load balancing

upstream backend {
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com;
}

server {
    listen 80;
    server_name example.com;
    
    location / {
        proxy_pass http://backend;
    }
}

Gewogen load balancing

upstream backend {
    server backend1.example.com weight=5;
    server backend2.example.com weight=2;
    server backend3.example.com;
}

IP-hash load balancing

upstream backend {
    ip_hash;
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com down;
}

Minste verbindingen

upstream backend {
    least_conn;
    server backend1.example.com;
    server backend2.example.com;
}

SSL/TLS-configuratie

Basis-HTTPS-configuratie

server {
    listen 443 ssl http2;
    server_name example.com;
    
    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;
    
    # SSL protocol versions
    ssl_protocols TLSv1.2 TLSv1.3;
    
    # SSL cipher suites
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;
    
    # HSTS
    add_header Strict-Transport-Security "max-age=63072000" always;
    
    location / {
        root /var/www/html;
        index index.html;
    }
}

Omleiding van HTTP naar HTTPS

server {
    listen 80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

Gangbare configuratievoorbeelden

PHP-FPM-configuratie

server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    index index.php index.html;
    
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
    
    location ~ /\.ht {
        deny all;
    }
}

Node.js-proxy

server {
    listen 80;
    server_name example.com;
    
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Configuratie voor snelheidsbeperking

# Connection-based rate limiting
limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
    location / {
        limit_conn addr 10;
    }
}

# Request rate limiting
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;

server {
    location / {
        limit_req zone=one burst=20 nodelay;
    }
}

Configuratie voor protectie tegen hotlinking

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    valid_referers none blocked example.com *.example.com;
    
    if ($invalid_referer) {
        return 403;
    }
}

Logboekbeheer

Eigen logformaat

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for"';

access_log /var/log/nginx/access.log main;

Voorwaardelijke logging

map $request_uri $loggable {
    ~^/health-check 0;
    default 1;
}

access_log /var/log/nginx/access.log combined if=$loggable;

Logrotatie

Gebruik logrotate voor logrotatie:

# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
}