Advanced Nginx configuration on VPS - Virtual Host SSL Gzip

Table of Contents

Why Advanced Nginx Configuration Matters

Nginx (pronounced Engine-X) is the world's most popular web server in 2026, used by over 34% of all websites. Its event-driven, non-blocking I/O architecture allows it to handle tens of thousands of concurrent connections with minimal RAM usage compared to Apache.

A default apt install nginx gets you a working server, but a production VPS requires properly tuned configuration for performance, security, and reliability.

SettingDefault ConfigOptimized Config
Worker Processes1= Number of CPU cores
Worker Connections7681024–65535
GzipDisabledEnabled, level 5
SSL ProtocolsTLSv1 TLSv1.1 TLSv1.2TLSv1.2 TLSv1.3 only
Security HeadersNoneHSTS, CSP, X-Frame-Options
Rate LimitingNoneLimit req/s per IP
FastCGI CacheDisabledEnabled for WordPress

Installation and File Structure

Install Nginx on Ubuntu 22.04/24.04 LTS:

sudo apt update && sudo apt install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginx

Key File Locations

Optimized nginx.conf

user www-data;
worker_processes auto;    # Uses all available CPU cores
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 1024;
    multi_accept on;
    use epoll;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    server_tokens off;    # Hide Nginx version number

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    gzip on;    # See Gzip section below

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

Tip: server_tokens off hides the Nginx version from HTTP response headers and error pages, preventing attackers from identifying version-specific vulnerabilities.

Virtual Hosts (Server Blocks)

Nginx calls its virtual hosts Server Blocks. Multiple domains can share a single IP address using SNI (Server Name Indication).

Creating a Server Block

sudo nano /etc/nginx/sites-available/example.com
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    root /var/www/example.com/public;
    index index.php index.html index.htm;

    # PHP-FPM handler
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    # Block .htaccess access
    location ~ /\.ht {
        deny all;
    }

    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;
}
# Enable the server block
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t        # Test configuration
sudo nginx -s reload # Apply changes

SSL/TLS Configuration

In 2026, SSL is mandatory for all production websites. Use Let's Encrypt for free SSL certificates:

Installing Certbot

sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com

Hardened SSL Configuration

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name example.com www.example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # Only allow TLS 1.2 and 1.3
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers off;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;

    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 1.1.1.1 8.8.8.8 valid=300s;

    # Session cache
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;

    root /var/www/example.com/public;
    # ... rest of config
}

# Redirect HTTP to HTTPS
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

⚠️ Important: Never enable TLSv1 or TLSv1.1 on production servers — both have known vulnerabilities. Use only TLSv1.2 and TLSv1.3. Test your SSL grade at SSL Labs.

Gzip Compression

Gzip reduces the size of text-based files by 60-80%. Add to the http {} block in nginx.conf:

gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 5;        # Level 1-9 (5 = balance CPU vs compression ratio)
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_min_length 256;      # Don't compress files smaller than 256 bytes
gzip_types
    application/atom+xml
    application/geo+json
    application/javascript
    application/x-javascript
    application/json
    application/ld+json
    application/manifest+json
    application/rdf+xml
    application/rss+xml
    application/xhtml+xml
    application/xml
    font/eot
    font/otf
    font/ttf
    image/svg+xml
    text/css
    text/javascript
    text/plain
    text/xml;

Note: Do not add already-compressed formats (JPEG, PNG, WebP, GIF, ZIP, MP4) to gzip_types — they won't compress further and will waste CPU cycles.

Security Headers

Security headers protect against common web attacks. Add to your server block:

add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;

# HSTS — Enable after SSL is confirmed working for at least 1 week
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
HeaderProtects Against
X-Frame-Options: SAMEORIGINClickjacking attacks
X-Content-Type-Options: nosniffMIME-type confusion attacks
Referrer-PolicyInformation leakage via referrer
X-XSS-ProtectionReflected XSS (legacy browser support)
Strict-Transport-SecuritySSL stripping, MITM attacks
Permissions-PolicyUnauthorized browser API access

Rate Limiting

Rate limiting restricts the number of requests a single IP can make, protecting against DDoS attacks and brute force login attempts:

# Add to http {} block in nginx.conf
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;
# WordPress login protection
location = /wp-login.php {
    limit_req zone=login burst=3 nodelay;
    limit_conn addr 3;
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
}

# API endpoints
location /api/ {
    limit_req zone=api burst=20 nodelay;
    proxy_pass http://backend;
}

Caching and Reverse Proxy

FastCGI Cache stores PHP output on disk, serving cached responses up to 50x faster than generating them on each request:

# Add to http {} block
fastcgi_cache_path /tmp/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
# In server {} block
set $skip_cache 0;

# Skip cache: POST requests, query strings, logged-in users
if ($request_method = POST) { set $skip_cache 1; }
if ($query_string != "") { set $skip_cache 1; }
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_logged_in") {
    set $skip_cache 1;
}

location ~ \.php$ {
    fastcgi_cache WORDPRESS;
    fastcgi_cache_valid 200 60m;
    fastcgi_cache_bypass $skip_cache;
    fastcgi_no_cache $skip_cache;
    add_header X-FastCGI-Cache $upstream_cache_status;
}

Reverse Proxy for Node.js / Python

server {
    listen 443 ssl http2;
    server_name app.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_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;
        proxy_cache_bypass $http_upgrade;
    }
}

WordPress Optimization

WordPress on Nginx requires specific configuration since Nginx doesn't support .htaccess. Use the try_files directive for pretty permalinks:

server {
    listen 443 ssl http2;
    server_name myblog.com www.myblog.com;
    root /var/www/myblog.com/public;
    index index.php;

    # WordPress permalink handling
    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    # Block direct PHP access to uploads and sensitive files
    location ~* /(?:uploads|files)/.*\.php$ { deny all; }
    location = /xmlrpc.php { deny all; }

    # Browser caching for static assets
    location ~* \.(css|js|png|jpg|jpeg|gif|webp|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        access_log off;
    }

    location ~ \.php$ {
        try_files $uri =404;
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
        fastcgi_param HTTP_PROXY "";
    }

    location ~ /\.ht { deny all; }
}

Testing and Debugging

Always test your configuration before reloading Nginx:

# Test configuration syntax
sudo nginx -t

# Expected output:
# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful

# Reload without stopping service
sudo nginx -s reload
# or
sudo systemctl reload nginx

Monitoring Logs in Real Time

# Access log
sudo tail -f /var/log/nginx/access.log

# Error log (critical for debugging)
sudo tail -f /var/log/nginx/error.log

# Domain-specific log
sudo tail -f /var/log/nginx/example.com.error.log

Production Nginx Checklist

Frequently Asked Questions

What is the difference between Nginx and Apache?
Nginx uses an event-driven, non-blocking I/O model that handles thousands of concurrent connections with minimal RAM. Apache uses a process/thread-per-connection model that consumes more memory at scale. For VPS hosting with high traffic, Nginx is generally preferred for performance and lower resource footprint, especially when combined with PHP-FPM and FastCGI caching.
How much RAM does Nginx require on a VPS?
Each Nginx worker process uses approximately 5-15 MB of RAM. A 1 GB RAM VPS can comfortably run Nginx + PHP-FPM + MariaDB for small to medium sites. For WordPress with high traffic or multiple domains, 2 GB or more is recommended.
How do I test Nginx configuration before reloading?
Run sudo nginx -t to test all configuration syntax. A passing test shows "syntax is ok" and "test is successful". Then use sudo nginx -s reload to apply changes without stopping the service. If the config is invalid, Nginx won't reload and your site continues running normally.
How much does Gzip improve website performance?
Gzip typically reduces HTML, CSS, and JavaScript file sizes by 60-80%, significantly improving page load times especially on slower connections. Skip Gzip for already-compressed formats like JPEG, PNG, WebP, ZIP, and MP4 as they won't benefit and will waste CPU cycles.
Does Nginx support .htaccess files?
No, Nginx does not support .htaccess files. All configuration must be in server block files. For WordPress, use the try_files $uri $uri/ /index.php?$args; directive instead of .htaccess rewrite rules. This is actually more performant as there's no need to check for .htaccess files on every request.
How do I set up Nginx as a reverse proxy for Node.js?
Configure an Nginx server block with a proxy_pass directive pointing to your Node.js application port (e.g., http://127.0.0.1:3000). Include proxy headers like X-Real-IP and X-Forwarded-For so your app sees the actual client IP. Add proxy_http_version 1.1 and Connection upgrade headers for WebSocket support.

Need a VPS for Nginx?

AsiaGB offers VPS Thailand and Singapore with fast SSD storage, 99% Uptime, supporting Ubuntu 22.04/24.04. Deploy Nginx and start your projects immediately.

View VPS Packages →