CSchantz Wiki

Possible Cpanel Nginx and Virsh setup instructons

cPanel + Nginx + Varnish Setup Guide

cPanel + Nginx + Varnish Setup Guide

⚠️ Warning: This configuration is NOT officially supported by cPanel and may break during cPanel updates. Proceed with caution on production servers.

Overview

This guide shows how to add Varnish caching between cPanel's built-in Nginx reverse proxy and Apache for maximum performance.

✓ Full SSL/HTTPS Support: This setup fully supports both HTTP and HTTPS. Nginx handles all SSL certificates automatically through cPanel's AutoSSL or Let's Encrypt.

Architecture Flow

Client → Nginx (80/443) → Varnish (81) → Apache (8080/8443)


Visual Diagram

CLIENT (Browser)
     ↓
[HTTP Port 80 OR HTTPS Port 443]
     ↓
┌─────────────────────────────────┐
│ NGINX (Ports 80 & 443)          │
│                                 │
│ HTTP Request (Port 80):         │
│   ↓ Pass through to Varnish    │
│                                 │
│ HTTPS Request (Port 443):       │
│   ↓ Decrypt SSL Certificate    │
│   ↓ Convert HTTPS → HTTP        │
│   ↓ Pass to Varnish as HTTP     │
│                                 │
│ ← Managed by cPanel/AutoSSL     │
└──────────────┬──────────────────┘
               ↓ 
      [HTTP Only - Port 81]
               ↓
┌─────────────────────────────────┐
│ VARNISH (Port 81)               │
│ - HTTP cache ONLY               │
│ - Receives HTTP from Nginx      │
│ - Caches responses              │
│ - VCL rules apply               │
└──────────────┬──────────────────┘
               ↓
      [HTTP - Port 8080]
               ↓
┌─────────────────────────────────┐
│ APACHE (Port 8080 & 8443)       │
│ - PHP processing                │
│ - Database queries              │
│ - cPanel integration            │
│ - .htaccess support             │
└─────────────────────────────────┘

KEY POINTS:
• Nginx handles ALL SSL/HTTPS (certificates, encryption)
• Varnish only sees HTTP traffic (Nginx converts HTTPS→HTTP)
• Apache processes PHP on backend ports
• SSL certificates work automatically via cPanel

SSL/HTTPS - How It Works

🔒 HTTPS Traffic Flow

  1. Client sends HTTPS request to https://yourdomain.com (port 443)
  2. Nginx receives encrypted request on port 443
  3. Nginx decrypts using SSL certificate (managed by cPanel)
  4. Nginx converts HTTPS → HTTP and sends to Varnish on port 81
  5. Varnish caches/processes the HTTP request
  6. Response goes back through Varnish → Nginx
  7. Nginx encrypts response and sends as HTTPS to client
<p><strong>Result:</strong> Your visitors see HTTPS, but Varnish works with HTTP internally. This is normal and secure!</p>

Before You Begin

Prerequisites

Backup Everything First!

# Run these backup commands BEFORE starting
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup.$(date +%F)
cp /etc/nginx/ea-nginx.conf /etc/nginx/ea-nginx.conf.backup.$(date +%F)
cp /var/cpanel/cpanel.config /var/cpanel/cpanel.config.backup.$(date +%F)

Step 1: Enable cPanel's Nginx Reverse Proxy

Important: This step automatically sets up Nginx on ports 80/443 and moves Apache to ports 8080/8443. It also handles ALL SSL certificates automatically.
  1. Login to WHM as root
  2. Navigate to: Software → EasyApache 4
  3. Search for "nginx"
  4. Check the box next to: ea-nginx
  5. Click "Review" then "Provision"
  6. Wait for installation to complete
  7. Go to: Service Configuration → Nginx Reverse Proxy Global Configuration
  8. Click "Enable" to activate the reverse proxy

Option B: Via Command Line

yum install ea-nginx -y
/scripts/rebuildhttpdconf
systemctl restart nginx
systemctl restart httpd

Verify Nginx is Running

systemctl status nginx
netstat -tlnp | grep nginx

Should show:

Nginx listening on 0.0.0.0:80 (HTTP)

Nginx listening on 0.0.0.0:443 (HTTPS)

Test Your Domains Work

# Replace yourdomain.com with your actual domain
curl -I http://yourdomain.com
curl -I https://yourdomain.com

Both should return "200 OK" or "301 Moved"

✓ At this point: Nginx is handling ports 80/443, Apache is on 8080/8443, and SSL certificates work automatically!

Step 2: Install Varnish

Add Varnish Repository (Varnish 7.0 LTS)

curl -s https://packagecloud.io/install/repositories/varnishcache/varnish70/script.rpm.sh | bash

Install Varnish

yum install varnish -y
systemctl enable varnish

Step 3: Configure Varnish to Listen on Port 81

Why port 81? Varnish sits between Nginx (80/443) and Apache (8080). Port 81 is the standard choice for this middle layer.

Edit Varnish systemd Service

systemctl edit --full varnish

Find the ExecStart line and change it to:

ExecStart=/usr/sbin/varnishd -a :81 -f /etc/varnish/default.vcl -s malloc,256m

Save and exit (Ctrl+X, then Y, then Enter), then reload systemd:

systemctl daemon-reload

Step 4: Configure Varnish VCL (Backend to Apache)

Backup Original Config

cp /etc/varnish/default.vcl /etc/varnish/default.vcl.backup

Edit Varnish Configuration

nano /etc/varnish/default.vcl

Complete VCL Configuration

vcl 4.1;

Backend definition - Apache on port 8080

backend default {
.host = "127.0.0.1";
.port = "8080";
.connect_timeout = 600s;
.first_byte_timeout = 600s;
.between_bytes_timeout = 600s;
}

Normalize host header (for multi-domain support)

sub vcl_recv {
# Normalize the host header
set req.http.Host = regsub(req.http.Host, ":0-9+", "");

# Don't cache admin/login pages for ANY domain
if (req.url ~ "^/wp-admin" || 
    req.url ~ "^/wp-login.php" || 
    req.url ~ "^/cpanel" || 
    req.url ~ "^/webmail" ||
    req.url ~ "^/whm" ||
    req.url ~ "^/administrator") {
    return (pass);
}

# Don't cache POST requests
if (req.method == "POST") {
    return (pass);
}

# Don't cache if there's a shopping cart cookie (e-commerce sites)
if (req.http.Cookie ~ "cart" || 
    req.http.Cookie ~ "woocommerce" || 
    req.http.Cookie ~ "comment_" || 
    req.http.Cookie ~ "wordpress_logged_in") {
    return (pass);
}

# Don't cache requests with cookies (except static files)
if (req.http.Cookie && req.url !~ "\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm|woff|woff2|ttf|svg|webp|mp4|mp3)$") {
    return (pass);
}

# Cache static files - remove cookies
if (req.url ~ "\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm|woff|woff2|ttf|svg|webp|mp4|mp3)$") {
    unset req.http.Cookie;
    return (hash);
}

# Pass everything else through for now (can optimize later)
return (pass);

}

sub vcl_backend_response {
# Cache static content for 1 hour
if (bereq.url ~ ".(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm|woff|woff2|ttf|svg|webp)$") {
set beresp.ttl = 1h;
unset beresp.http.set-cookie;
}

# Cache HTML pages for 5 minutes (adjust as needed)
if (beresp.http.Content-Type ~ "text/html") {
    set beresp.ttl = 5m;
}

# Don't cache if backend returns errors
if (beresp.status == 500 || beresp.status == 502 || beresp.status == 503 || beresp.status == 504) {
    set beresp.ttl = 0s;
    return (deliver);
}

# Remove cookies from cached content
if (beresp.ttl > 0s) {
    unset beresp.http.set-cookie;
}

}

sub vcl_deliver {
# Add header to show if request was cached
if (obj.hits > 0) {
set resp.http.X-Cache = "HIT";
set resp.http.X-Cache-Hits = obj.hits;
} else {
set resp.http.X-Cache = "MISS";
}

# Add Varnish identifier
set resp.http.X-Served-By = "Varnish";

# Remove backend headers that expose server info (optional security)
unset resp.http.X-Powered-By;
unset resp.http.Server;

}

✓ Multi-Domain Support: This VCL configuration works for ALL domains on your cPanel server automatically. No need to specify individual domains!

Test VCL Configuration

varnishd -C -f /etc/varnish/default.vcl

Should show compiled VCL with no errors


Step 5: Modify Nginx to Proxy to Varnish

⚠️ Critical Step: This is where we insert Varnish between Nginx and Apache. cPanel may overwrite these changes during updates!

Method 1: Edit Main Nginx Proxy Config (Affects All Domains)

nano /etc/nginx/conf.d/ea-nginx.conf

Find all instances of proxy_pass http://127.0.0.1:8080; and change to:

proxy_pass http://127.0.0.1:81;

Example - BEFORE:

location / {
    proxy_pass http://127.0.0.1:8080;
    # ... other settings
}

Example - AFTER:

location / {
    proxy_pass http://127.0.0.1:81;  # Now points to Varnish!
    # ... other settings
}

Ensure These Proxy Headers Are Present

Make sure the following headers are set in the proxy configuration:

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_set_header X-Forwarded-Port $server_port;

Method 2: Per-Domain Configuration (Advanced)

If you only want Varnish for specific domains:

# Domain configs are in:
ls /etc/nginx/conf.d/users/

Edit specific domain config:

nano /etc/nginx/conf.d/users/USERNAME/DOMAIN.conf

Change proxy_pass for that domain only

Test Nginx Configuration

nginx -t

Should show:

nginx: configuration file /etc/nginx/nginx.conf test is successful


Step 6: Configure SSL/HTTPS Pass-through

✓ Good News: SSL/HTTPS should work automatically! cPanel's Nginx handles all SSL certificates and passes decrypted traffic to Varnish.

Verify HTTPS Configuration

# Check Nginx HTTPS config
grep -r "listen 443" /etc/nginx/conf.d/

Should show SSL configurations for your domains

SSL Certificates Are Managed Here

All SSL certificates continue to work normally - no changes needed!


Step 7: Start Services and Test

Start Varnish

systemctl start varnish
systemctl status varnish

Should show "active (running)"

Restart Nginx

systemctl restart nginx
systemctl status nginx

Should show "active (running)"

Verify All Services Are Running on Correct Ports

netstat -tlnp | grep -E '(:80|:81|:443|:8080)'

Expected output:

tcp  0  0.0.0.0:80      0.0.0.0:*  LISTEN  12345/nginx         ← Nginx HTTP
tcp  0  0.0.0.0:443     0.0.0.0:*  LISTEN  12345/nginx         ← Nginx HTTPS
tcp  0  0.0.0.0:81      0.0.0.0:*  LISTEN  67890/varnishd      ← Varnish
tcp  0  0.0.0.0:8080    0.0.0.0:*  LISTEN  11111/httpd         ← Apache HTTP
tcp  0  0.0.0.0:8443    0.0.0.0:*  LISTEN  11111/httpd         ← Apache HTTPS

Step 8: Test Your Domains (HTTP & HTTPS)

🔍 Testing Instructions: Replace yourdomain.com with your actual domain name in ALL commands below!

Test HTTP (Port 80)

# Replace yourdomain.com with YOUR domain!
curl -I http://yourdomain.com

Look for these headers:

HTTP/1.1 200 OK
X-Cache: MISS              ← First request is not cached
X-Served-By: Varnish       ← Confirms Varnish is working
Via: 1.1 varnish           ← Confirms Varnish is in the chain

Test Again (Should Be Cached)

# Same domain - second request
curl -I http://yourdomain.com

Should now show:

HTTP/1.1 200 OK
X-Cache: HIT               ← NOW it's cached!
X-Cache-Hits: 1            ← Hit counter
X-Served-By: Varnish

Test HTTPS (Port 443)

# Replace yourdomain.com with YOUR domain!
curl -I https://yourdomain.com

Should show:

HTTP/2 200                 ← HTTP/2 means HTTPS is working!
X-Cache: MISS              ← First request
X-Served-By: Varnish
Via: 1.1 varnish

Test HTTPS Again (Should Be Cached)

curl -I https://yourdomain.com

Should show:

HTTP/2 200
X-Cache: HIT               ← Cached!
X-Cache-Hits: 1
X-Served-By: Varnish

Test Multiple Domains

# If you have multiple domains, test each one:
curl -I http://domain1.com
curl -I https://domain1.com
curl -I http://domain2.com
curl -I https://domain2.com

All should show Varnish headers

Test in Your Browser

  1. Open your website: https://yourdomain.com
  2. Press F12 to open Developer Tools
  3. Go to Network tab
  4. Refresh the page (Ctrl+R)
  5. Click on the first request (your domain)
  6. Look at Response Headers
  7. You should see: X-Cache: HIT or MISS and X-Served-By: Varnish
✓ Success! If you see the X-Cache and X-Served-By headers, Varnish is working correctly for both HTTP and HTTPS!

Domain-Specific Configuration (If Needed)

When You Add New Domains to cPanel

Good news: New domains will automatically work with this setup! cPanel's Nginx will create configurations for them, and Varnish handles all domains through the same VCL.

If a Specific Domain Isn't Working

# Check if domain has Nginx config:
ls -la /etc/nginx/conf.d/users/*/yourdomain.com.conf

# Check if proxy_pass points to Varnish:
grep "proxy_pass" /etc/nginx/conf.d/users/*/yourdomain.com.conf

# Should show: proxy_pass http://127.0.0.1:81;

Exclude a Domain from Varnish (Optional)

If you want a specific domain to bypass Varnish:

# Edit that domain's Nginx config
nano /etc/nginx/conf.d/users/USERNAME/domain.com.conf

Change proxy_pass back to Apache:

proxy_pass http://127.0.0.1:8080; # Direct to Apache

Test and reload:

nginx -t
systemctl reload nginx


SSL Certificate Renewal

✓ Automatic: SSL certificate renewals work automatically! cPanel's AutoSSL/Let's Encrypt continues to work normally because Nginx handles all SSL.

How SSL Renewal Works

  1. cPanel/AutoSSL automatically renews certificates (usually every 60-80 days)
  2. Nginx automatically loads new certificates
  3. No manual intervention needed
  4. Varnish is not affected (it only handles HTTP)

Manual SSL Certificate Installation

If you need to install a custom SSL certificate:

  1. Go to cPanel → SSL/TLS Status
  2. Install certificate as normal
  3. Nginx will automatically use it
  4. No changes needed to Varnish configuration

Monitoring and Maintenance

View Varnish Statistics in Real-Time

varnishstat

Press 'q' to quit

View Varnish Logs

# View all requests
varnishlog

View only cache hits

varnishlog -q "VCL_call eq 'HIT'"

View only cache misses

varnishlog -q "VCL_call eq 'MISS'"

View requests for specific domain

varnishlog -q "ReqHeader:Host ~ 'yourdomain.com'"

Clear Varnish Cache

# Clear ALL cache
varnishadm "ban req.url ~ /"

Clear cache for specific domain

varnishadm "ban req.http.host == yourdomain.com"

Clear cache for specific URL pattern

varnishadm "ban req.url ~ /wp-content/"

Check Varnish Backend Health

varnishadm backend.list

Should show:

Backend name: default

Status: Healthy

Check What's Being Cached

# See cache statistics
varnishstat -1 | grep -E 'cache_hit|cache_miss'

Example output:

MAIN.cache_hit 15234 ← Requests served from cache

MAIN.cache_miss 1523 ← Requests that needed backend


Troubleshooting

Issue Solution
No X-Cache headers showing 1. Check Varnish is running: systemctl status varnish
2. Check Nginx is proxying to port 81: grep "proxy_pass" /etc/nginx/ea-nginx.conf
3. Check ports: netstat -tlnp | grep -E '(:81|:8080)'
4. Test VCL: varnishd -C -f /etc/varnish/default.vcl
HTTPS not working 1. Check Nginx is on 443: netstat -tlnp | grep :443
2. Check SSL cert exists: ls -la /etc/ssl/cpanel/
3. Rebuild config: /scripts/rebuildhttpdconf
4. Check browser for certificate errors
5. Test: curl -I https://yourdomain.com
Site loads but no caching 1. Check VCL rules - might be passing instead of caching
2. Check for cookies: curl -I http://yourdomain.com | grep Set-Cookie
3. View logs: varnishlog -q "ReqURL ~ '^/'"
4. Most dynamic pages won't cache by default (this is normal)
Specific domain not working 1. Check domain exists in cPanel
2. Check Nginx config: ls /etc/nginx/conf.d/users/*/yourdomain.com*
3. Check DNS points to server
4. Test direct: curl -I http://yourdomain.com
5. Check logs: tail -f /var/log/nginx/error.log
500/502/503 errors 1. Check Apache is running: systemctl status httpd
2. Check port 8080: curl -I http://127.0.0.1:8080
3. Check Apache logs: tail -f /usr/local/apache/logs/error_log
4. Check Varnish backend: varnishadm backend.list
5. Restart services: systemctl restart varnish httpd nginx
cPanel update broke config 1. Check Nginx config: nginx -t
2. Verify proxy_pass still points to :81
3. Restore from backup if needed
4. Rebuild: /scripts/rebuildhttpdconf
5. Re-edit: nano /etc/nginx/ea-nginx.conf
6. Restart: systemctl restart nginx
WordPress admin not working VCL should exclude /wp-admin and /wp-login.php
If still cached, clear cache: varnishadm "ban req.url ~ /wp-"
Or add to VCL: if (req.url ~ "^/wp-") { return (pass); }

Performance Tuning (Optional)

Increase Varnish Memory

systemctl edit --full varnish

Change memory allocation based on your server RAM:

# For 4GB RAM server:
-s malloc,512m

For 8GB RAM server:

-s malloc,1G

For 16GB RAM server:

-s malloc,2G

Enable Caching for More Content Types

Edit /etc/varnish/default.vcl and adjust TTL (time to live):

sub vcl_backend_response {
    # Cache HTML pages for longer
    if (beresp.http.Content-Type ~ "text/html") {
        set beresp.ttl = 15m;  # Was 5m, now 15 minutes
    }
# Cache API responses
if (bereq.url ~ "^/api/") {
    set beresp.ttl = 2m;
}

}

Monitor Cache Hit Ratio

varnishstat -1 | grep cache_hit

Good hit ratio is >80%

Calculate: cache_hit / (cache_hit + cache_miss) * 100


Backup Commands

Before Making Changes

# Backup all critical configs
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.backup.$(date +%F)
cp /etc/nginx/ea-nginx.conf /etc/nginx/ea-nginx.conf.backup.$(date +%F)
cp /etc/varnish/default.vcl /etc/varnish/default.vcl.backup.$(date +%F)

After Successful Setup

# Create a complete working backup
mkdir -p /root/backups/nginx-varnish-working
cp /etc/nginx/ea-nginx.conf /root/backups/nginx-varnish-working/
cp /etc/varnish/default.vcl /root/backups/nginx-varnish-working/
echo "Backup created: $(date)" > /root/backups/nginx-varnish-working/README.txt

Rollback Instructions

If You Need to Remove Varnish

# 1. Stop Varnish
systemctl stop varnish
systemctl disable varnish

# 2. Edit Nginx back to Apache
nano /etc/nginx/ea-nginx.conf

# Change:
# proxy_pass http://127.0.0.1:81;
# Back to:
# proxy_pass http://127.0.0.1:8080;

# 3. Test and restart Nginx
nginx -t
systemctl restart nginx

# 4. Optional: Remove Varnish completely
yum remove varnish -y

Restore from Backup

# Restore Nginx config
cp /etc/nginx/ea-nginx.conf.backup.YYYY-MM-DD /etc/nginx/ea-nginx.conf

Restore Varnish config (if needed)

cp /etc/varnish/default.vcl.backup.YYYY-MM-DD /etc/varnish/default.vcl

Restart services

systemctl restart nginx varnish


Summary Checklist

✅ Verify Everything is Working:

  • ☐ Nginx running on ports 80 & 443
  • ☐ Varnish running on port 81
  • ☐ Apache running on ports 8080 & 8443
  • ☐ HTTP works: curl -I http://yourdomain.com shows X-Cache header
  • ☐ HTTPS works: curl -I https://yourdomain.com shows X-Cache header
  • ☐ Browser shows HTTPS padlock
  • ☐ All domains tested and working
  • ☐ Cache hits increasing: varnishstat
  • ☐ No errors in logs: tail /var/log/nginx/error.log
  • ☐ Backups created

Key Takeaways

✓ What Works Automatically

  • All domains work through this setup (no per-domain config needed)
  • SSL/HTTPS works automatically via cPanel's Nginx
  • SSL renewals happen automatically (AutoSSL/Let's Encrypt)
  • New domains added to cPanel work immediately
  • cPanel features continue to work (email, FTP, databases, etc.)

⚠️ Watch Out For

  • cPanel updates may reset Nginx config - check after updates
  • Cache needs clearing when you update site content
  • Admin pages should bypass cache (configured in VCL)
  • E-commerce sites need special cache rules (shopping carts, checkouts)
  • This setup is not officially supported by cPanel
  • cPanel support may refuse to help with issues
  • Updates may break configuration without warning
  • More complex to troubleshoot than standard cPanel

Additional Resources


Last Updated: January 2026

Questions? Test thoroughly on a staging server before production!