Master Nginx: From Installation to Advanced Production Tuning

This comprehensive guide walks you through installing Nginx on Linux and Windows, configuring basic and advanced settings, securing the server, optimizing performance, setting up load balancing, caching, HTTPS, and monitoring with Prometheus, providing practical commands and examples for production environments.

Ray's Galactic Tech
Ray's Galactic Tech
Ray's Galactic Tech
Master Nginx: From Installation to Advanced Production Tuning

Quick Installation and Startup Cheat Sheet

# Ubuntu/Debian
sudo apt update && sudo apt install nginx -y
sudo systemctl --now enable nginx

# CentOS/RHEL
sudo yum install epel-release -y && sudo yum install nginx -y
sudo systemctl --now enable nginx

# Test access
curl http://127.0.0.1

Detailed Installation (Linux)

Ubuntu/Debian

# Update package list
sudo apt update

# Install Nginx
sudo apt install nginx

# Start Nginx
sudo systemctl start nginx

# Enable on boot
sudo systemctl enable nginx

CentOS/RHEL

# Install EPEL repository (required for CentOS/RHEL)
sudo yum install epel-release -y

# Update and install Nginx
sudo yum update
sudo yum install nginx -y

# Start Nginx
sudo systemctl start nginx

# Enable on boot
sudo systemctl enable nginx

Source Compilation (Custom Build)

# Install build dependencies
sudo yum install -y gcc pcre-devel openssl-devel zlib-devel
# or on Ubuntu
sudo apt install -y build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev

# Download source (example: Nginx 1.25.3)
wget https://nginx.org/download/nginx-1.25.3.tar.gz
tar -xzvf nginx-1.25.3.tar.gz
cd nginx-1.25.3

# Configure (custom paths/modules)
./configure --prefix=/usr/local/nginx --with-http_ssl_module

# Build and install
make
sudo make install

# Start Nginx
sudo /usr/local/nginx/sbin/nginx

Windows Installation

Download the Windows zip package from the official site (e.g., nginx-1.25.3.zip).

Extract to any directory, such as C:\nginx.

Start Nginx either by running cd C:\nginx && start nginx in a command prompt or by double‑clicking nginx.exe.

Verify by opening a browser to http://localhost and seeing the "Welcome to nginx!" page.

Basic Commands and Firewall

# Show version
nginx -v
# Test configuration syntax
nginx -t
# Start Nginx
nginx
# Reload configuration
nginx -s reload
# Graceful stop
nginx -s quit

# Open HTTP port in firewalld (CentOS/RHEL)
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --reload

Core Feature Configuration (Practical Optimizations)

1. Static File Service

server {
    listen 80;
    server_name localhost;
    location / {
        root /opt/static;
        index index.html;
    }
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        root /opt/static;
        expires 30d;
    }
}

2. Reverse Proxy with Timeouts and Error Handling

server {
    listen 80;
    server_name example.com;
    location / {
        proxy_pass http://127.0.0.1:8080;
        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_connect_timeout 5s;
        proxy_send_timeout 10s;
        proxy_read_timeout 30s;
        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
            root /usr/share/nginx/html;
        }
    }
}

3. Load Balancing with Health Checks

upstream backend {
    least_conn;
    server 192.168.1.101:8080 max_fails=3 fail_timeout=30s;
    server 192.168.1.102:8080 max_fails=3 fail_timeout=30s;
}

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

4. Caching Acceleration

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

server {
    listen 80;
    server_name cache.example.com;
    location / {
        proxy_cache my_cache;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        proxy_pass http://backend;
    }
}

5. HTTPS Configuration

server {
    listen 443 ssl;
    server_name secure.example.com;
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
    ssl_session_cache shared:SSL:1m;
    ssl_session_timeout 5m;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;
    location / {
        root html;
        index index.html index.htm;
    }
}
# Redirect HTTP to HTTPS
server {
    listen 80;
    server_name secure.example.com;
    return 301 https://$host$request_uri;
}

6. Security Hardening (Extended)

# Hide version information
server_tokens off;
# Limit upload size
client_max_body_size 10m;
# Restrict HTTP methods
if ($request_method !~ ^(GET|HEAD|POST)$) { return 405; }
# Rate limiting to mitigate bots / CC attacks
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=1r/s;
limit_req zone=req_limit burst=5 nodelay;
# Block known crawlers
if ($http_user_agent ~* (scrapy|curl|wget|python)) { return 403; }
# Security response headers
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'";

7. Performance Tuning (Production Recommendations)

events {
    worker_connections 10240;
    use epoll;
    multi_accept on;
}
http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    gzip on;
    gzip_types text/plain text/css application/json application/javascript;
    open_file_cache max=1000 inactive=20s;
    open_file_cache_valid 30s;
}

Monitoring and Operations

1. Nginx Runtime Status

location /nginx_status {
    stub_status on;
    allow 127.0.0.1;
    deny all;
}

2. Prometheus Exporter

nginx‑prometheus‑exporter provides metrics for scraping.

Combine with Grafana for visual dashboards.

3. Log Analysis

Real‑time: tail -f logs/access.log Graphical:

goaccess access.log -o report.html --log-format=COMBINED

Best‑Practice Checklist

Performance: enable gzip, HTTP/2, caching.

Security: enable rate limiting, anti‑scraping, TLS 1.3.

Operations: manage with systemd, rotate logs, monitor with Prometheus.

High Availability: load balancing with health checks.

Debugging: use nginx -t to test config and monitor error logs.

Conclusion

By following this guide you can deploy Nginx from scratch and apply the most common production‑grade optimizations, security hardening, and monitoring configurations. Adjust parameters continuously based on traffic and security requirements to fully leverage Nginx’s customizability.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

load balancing
Ray's Galactic Tech
Written by

Ray's Galactic Tech

Practice together, never alone. We cover programming languages, development tools, learning methods, and pitfall notes. We simplify complex topics, guiding you from beginner to advanced. Weekly practical content—let's grow together!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.