Nginx Configuration Optimization
7/1/24About 3 min
Nginx Configuration Optimization
Overview
Nginx is a high-performance HTTP and reverse proxy server widely used for load balancing, static asset serving, and SSL termination.
1. Installation and Basic Configuration
1.1 Install Nginx (Ubuntu)
# Update system
sudo apt-get update
# Install Nginx
sudo apt-get install -y nginx
# Start service
sudo systemctl start nginx
sudo systemctl enable nginx
# Verify installation
nginx -v1.2 Basic Configuration File
# /etc/nginx/nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
http {
sendfile on;
tcp_nopush on;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Logging configuration
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
# Enable gzip compression
gzip on;
gzip_types text/plain text/css application/json application/javascript;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}2. Reverse Proxy Configuration
2.1 Basic Reverse Proxy
# /etc/nginx/sites-available/my-app
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:5000;
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;
}
}2.2 Load Balancing
http {
# Define upstream server group
upstream backend {
server backend1.example.com:8080 weight=3;
server backend2.example.com:8080 weight=2;
server backend3.example.com:8080 weight=1;
# Health check
keepalive 64;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
}2.3 Load Balancing Algorithms
| Algorithm | Description |
|---|---|
| round_robin | Round robin (default) |
| least_conn | Least connections |
| ip_hash | Client IP hash |
| fair | Response time priority |
| url_hash | URL hash |
upstream backend {
ip_hash; # Use IP hash algorithm
server backend1.example.com;
server backend2.example.com;
}3. SSL/TLS Configuration
3.1 Configure HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com;
# SSL certificates
ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;
# SSL optimization
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
location / {
proxy_pass http://localhost:5000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
}
}3.2 Using Let's Encrypt
# Install Certbot
sudo apt-get install -y certbot python3-certbot-nginx
# Obtain certificate
sudo certbot --nginx -d example.com -d www.example.com
# Test automatic renewal
sudo certbot renew --dry-run4. Static Asset Optimization
4.1 Static File Serving
server {
listen 80;
server_name static.example.com;
root /var/www/static;
# Cache images for 30 days
location ~* \.(jpg|jpeg|png|gif|ico)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
# Cache CSS/JS for 7 days
location ~* \.(css|js)$ {
expires 7d;
add_header Cache-Control "public, immutable";
}
# Deny access to hidden files
location ~ /\. {
deny all;
}
}4.2 Gzip Compression
http {
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/javascript
application/xml+rss
application/json;
# Brotli compression (requires module installation)
brotli on;
brotli_types text/plain text/css application/json application/javascript;
}5. Security Configuration
5.1 Request Limiting
server {
# Limit request rate
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
location / {
limit_req zone=one burst=5;
proxy_pass http://localhost:5000;
}
# Limit request body size
client_max_body_size 10M;
# Deny access to sensitive directories
location ~ /\.git {
deny all;
}
# Security response headers
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
}5.2 Access Control
# Allow specific IPs
location /admin {
allow 192.168.1.0/24;
allow 10.0.0.0/8;
deny all;
proxy_pass http://localhost:5000;
}
# Basic authentication
location /api {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
proxy_pass http://localhost:5000;
}# Create password file
htpasswd -c /etc/nginx/.htpasswd username6. Performance Optimization
6.1 Worker Process Configuration
user www-data;
worker_processes auto; # Automatically set to CPU core count
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;
events {
worker_connections 10240;
use epoll;
multi_accept on;
}6.2 Connection Optimization
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 100;
client_body_buffer_size 128k;
client_header_buffer_size 1k;
large_client_header_buffers 4 4k;
}6.3 Cache Configuration
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g
inactive=60m use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_pass http://localhost:5000;
}
}7. Logging Configuration
7.1 Custom Log Format
http {
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;
error_log /var/log/nginx/error.log;
}7.2 Separate Logs by Domain
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/example.com.access.log main;
error_log /var/log/nginx/example.com.error.log;
location / {
proxy_pass http://localhost:5000;
}
}8. Status Monitoring
8.1 Enable Status Page
server {
listen 80;
server_name status.example.com;
location /nginx_status {
stub_status on;
access_log off;
allow 192.168.1.0/24;
deny all;
}
}8.2 Status Page Output
Active connections: 10
server accepts handled requests
1000 1000 5000
Reading: 1 Writing: 2 Waiting: 79. Virtual Host Configuration
9.1 Multi-Domain Configuration
server {
listen 80;
server_name example.com www.example.com;
location / {
proxy_pass http://localhost:5000;
}
}
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:5001;
}
}
server {
listen 80;
server_name static.example.com;
root /var/www/static;
}10. Troubleshooting
10.1 Check Configuration
# Check configuration syntax
nginx -t
# Reload configuration
nginx -s reload
# View logs
tail -f /var/log/nginx/error.log10.2 Common Issues
| Issue | Solution |
|---|---|
| 403 Forbidden | Check file permissions and directory index configuration |
| 502 Bad Gateway | Check whether the backend service is running |
| SSL certificate issues | Check certificate path and permissions |
| Connection timeout | Adjust proxy_timeout settings |
Summary
Nginx is a powerful web server. With proper configuration, it can deliver a high-performance, highly available service architecture. Mastering Nginx configuration is an essential skill for operations engineers.
Author: Lei Tao
Date: July 1, 2024