October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Set Up Varnish With Nginx and SSL

A practical guide to running Nginx as the HTTPS terminator, Varnish on a private listener, and an origin on port 8080—with VCL, headers, TLS alternatives, and troubleshooting.
Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The most straightforward arrangement is client HTTPS on Nginx port 443, Nginx forwarding plain HTTP to a private Varnish listener, and Varnish forwarding cache misses to an origin listener on Nginx or the application. A typical port plan is Nginx 443 for TLS, Varnish 127.0.0.1:6081 for caching, and the origin Nginx server on 127.0.0.1:8080. This gives you one deliberate TLS termination point, prevents the two services from fighting over a socket, and keeps the cache layer off the public network.

Varnish can terminate TLS itself, but that is a different design. Decide where certificates, HTTP protocol support, scheme headers, and backend encryption belong before changing listeners. Then validate each layer independently instead of treating a successful Nginx reload as proof that caching works.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the request path before changing ports

Every request must have an unambiguous route. In the common Nginx-fronted design, the path is:

Client
  │ HTTPS :443
  ▼
Nginx (TLS termination, redirects, request headers)
  │ HTTP 127.0.0.1:6081
  ▼
Varnish (VCL and cache policy)
  │ HTTP 127.0.0.1:8080
  ▼
Origin application or origin Nginx server

Nginx owns the public TLS socket. Varnish receives only the internal HTTP request and decides whether to serve an object from cache or contact the origin. The origin listener must be different from both public Nginx listeners, otherwise one service will fail to start or requests will loop back into the wrong layer.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

Port plan for the common layout

Component Address and port Purpose Exposure
Nginx HTTPS 0.0.0.0:443 (or the server’s public address) Client TLS, redirects, and proxying Public
Nginx HTTP redirect 0.0.0.0:80 Redirects HTTP clients to HTTPS Public
Varnish 127.0.0.1:6081 in this example Cache and VCL processing Private
Origin Nginx or application 127.0.0.1:8080 in the documented default Generates uncached responses Private

Port 6081 is Varnish’s conservative default in the service documentation. Port 80 is also used in examples where Varnish itself is the front proxy. Do not copy a port from one topology into another without checking which process is intended to own it.

What you need before installation

  • A Debian or Ubuntu server with administrative access and a systemd-based service manager.
  • A domain whose DNS points to the server, if the site will be reached by a hostname.
  • A certificate and private key for every HTTPS name you will serve. The example below uses the conventional paths under /etc/letsencrypt/live/; substitute the paths used by your certificate process.
  • An identified origin listener. Decide whether the origin is another Nginx server block, an application server, or a local socket translated to TCP by Nginx.
  • A cache policy from the application owner. Public, identical responses are candidates for caching; authenticated, personalized, checkout, cart, administrative, and state-changing requests normally are not.

Install Varnish from the official Varnish repository appropriate for the operating-system release. Package names and repository setup vary by distribution, so use the repository’s current installation instructions rather than assuming that a package from an unrelated release is compatible.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Install Varnish and inspect its service definition

After installation, inspect the service before editing it. The installation guide places the packaged unit at /lib/systemd/system/varnish.service. The unit determines the Varnish listener, VCL file, storage method, and cache size.

  1. Display the unit and its effective arguments with systemctl cat varnish.
  2. Identify the varnishd ExecStart line and note the current -a listener, -f VCL path, and storage argument.
  3. Choose a protected listener such as 127.0.0.1:6081 for the Nginx-fronted topology. Keep the distribution’s existing VCL and storage arguments unless you have a reason to change them.
  4. Make local service changes through a systemd drop-in or the distribution’s documented override mechanism. Avoid editing a package-managed unit in a way that an upgrade can silently overwrite.
  5. After any unit change, run sudo systemctl daemon-reload, then restart Varnish with sudo systemctl restart varnish.

The service must be listening on the address that Nginx will use. If Varnish binds to a public address by accident, firewall it or change the listener; the Nginx-to-Varnish hop is intended to be private in this design.

Move the origin Nginx listener away from port 80

If Nginx currently serves the origin on listen 80;, Varnish cannot also bind that socket. The Varnish quick-start changes the origin Nginx listener to port 8080 and then points the VCL backend at that port.

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed
  1. Open every relevant Nginx server block and distinguish the public redirect/TLS blocks from the origin block.
  2. Change the origin block’s listener to an internal address and port, for example listen 127.0.0.1:8080;. If the origin must serve several local names, preserve the appropriate server_name values.
  3. Review includes and additional files for other listen 80; directives. A recursive replacement can alter a health-check, management, or unrelated virtual host, so inspect the result rather than applying a blind search-and-replace.
  4. Run sudo nginx -t. Reload only if the syntax test succeeds: sudo systemctl reload nginx.

At this point, the origin should answer on 8080, while the eventual public server block will send requests to Varnish on 6081. Test the origin locally before adding cache behavior so that an origin failure is not confused with a VCL failure.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Define the Varnish backend in VCL

Edit /etc/varnish/default.vcl and make the backend match the origin listener exactly:

vcl 4.1;

backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

The documented default points to 127.0.0.1:8080. Replace both values when the origin uses another address or port. A hostname is allowed, but Varnish resolves DNS names when the VCL is compiled; after changing DNS, reload or recompile the VCL so the new address is used.

Start with generated behavior, then add narrowly scoped rules

The generated VCL provides the safest baseline while you confirm connectivity. Add policy only for responses that the application owner has identified as safe to share between visitors. A small example of request exclusions is:

sub vcl_recv {
    if (req.method != "GET" && req.method != "HEAD") {
        return (pass);
    }

    if (req.http.Authorization) {
        return (pass);
    }

    if (req.url ~ "^/(admin|cart|checkout)(/|$)") {
        return (pass);
    }
}

The path names are examples, not a universal application policy. Add your own account, API, preview, logout, search, or other personalized routes as needed. Do not remove cookies, authorization headers, or origin cache-control directives merely to increase the hit rate. If an application deliberately publishes a cookie-bearing response for everyone, document that exception before changing VCL.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Compile and apply the VCL

Use the Varnish service’s normal reload or restart procedure after editing the file. A syntax error prevents the new configuration from compiling; retain the last known-good VCL until the replacement has compiled successfully. If you changed the systemd unit as well as the VCL, run sudo systemctl daemon-reload first and then restart Varnish. Check the service status immediately afterward with sudo systemctl status varnish.

Configure Nginx to terminate HTTPS and proxy to Varnish

The public Nginx configuration needs one HTTP redirect server and one TLS server. Adapt the domain names and certificate paths:

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

server {
    listen 443 ssl;
    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;
    ssl_protocols       TLSv1.2 TLSv1.3;

    location / {
        proxy_pass http://127.0.0.1:6081;
        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 https;
    }
}

Nginx requires the ssl parameter on the TLS listening socket and paths for the certificate and private key. The example explicitly permits TLS 1.2 and TLS 1.3. Keep the private key readable only by the accounts that need it.

Why each proxy header matters

  • proxy_pass sends the request to Varnish instead of directly to the origin.
  • Host $host preserves the hostname used for virtual hosting, URL generation, and tenant selection.
  • X-Real-IP $remote_addr gives the upstream a direct client-address value.
  • X-Forwarded-For $proxy_add_x_forwarded_for appends the client address to the forwarding chain rather than replacing existing proxy information.
  • X-Forwarded-Proto https tells the application that the original client connection was HTTPS, even though the internal hop from Nginx to Varnish is HTTP.

Only trust forwarded-address and scheme headers from proxies you control. If the origin is directly reachable from an untrusted network, it must not be allowed to accept forged values as if they came from Nginx.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Run sudo nginx -t after editing. A successful test checks syntax and referenced files; it does not prove that Varnish is listening, that the backend is reachable, or that a response is cacheable. Reload Nginx only after the test succeeds.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Decide where TLS should terminate

There are three valid arrangements. They differ in certificate operations, protocol handling, exposure, and the encryption of internal hops.

Design Client-facing listener Internal connection When it fits Operational cost
Nginx terminates TLS Nginx on 443 HTTP from Nginx to private Varnish, then HTTP to the origin The common, simpler separation of TLS, proxying, and caching Certificates and TLS settings live in Nginx; the internal hop is unencrypted unless separately protected
Varnish terminates TLS Varnish can listen with an HTTPS address Varnish can forward HTTP or an encrypted backend connection You want Varnish at the edge or need its native TLS listener Certificate loading, startup arguments, and observability move into the Varnish layer
Encrypted Varnish-to-backend hop Either Nginx or Varnish handles client TLS Varnish backend uses HTTPS with .ssl = 1 The origin is on another host or policy requires encryption inside the deployment Backend certificate validation, names, ports, and failure handling must be configured

Using Varnish as the HTTPS listener

Varnish documents native HTTPS listeners using address arguments such as -a :80,http and -a :443,https. Its TLS setup also requires loading and committing certificates through the Varnish startup and certificate-management procedure. If Varnish owns port 443, Nginx must not also listen there; move Nginx to an internal origin port or place it behind Varnish.

This layout can be appropriate when the cache is the intended edge proxy, but it changes where you manage certificates and how you provide HTTP/2 or HTTP/3 capabilities. Confirm that the edge component and deployment support the protocols your clients require before choosing it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Encrypting the backend connection

For an HTTPS origin, define the backend on port 443 and set .ssl = 1 in the VCL backend definition. The origin’s certificate name, trust requirements, and SNI behavior must match the deployment. If the origin is local and the host is already protected, plain HTTP may be acceptable; the choice is an architectural and compliance decision, not a cache requirement.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Verify listeners and the complete request path

Validate in layers, from configuration files to the public endpoint:

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.
  1. Check Nginx syntax with sudo nginx -t. Do not reload after a failed test.
  2. Check the service state with sudo systemctl status nginx and sudo systemctl status varnish.
  3. List listening TCP sockets with sudo ss -ltnp. Confirm that Nginx owns 443 and 80, Varnish owns the selected private port, and the origin owns 8080. Investigate any duplicate listener.
  4. Request the public endpoint: curl -I https://example.com/. Confirm the certificate presented for the hostname, the HTTP-to-HTTPS redirect, and the expected response status.
  5. Request a known cacheable URL twice. Compare response headers and timing, but interpret them using the application’s cache policy rather than assuming that every second request must be a hit.
  6. Inspect headers such as Via, Age, or an application-specific cache marker when your configuration emits them. Their absence alone is not proof of failure if the service intentionally hides those headers.
  7. Test an authenticated URL and a state-changing request. Confirm that VCL passes them to the origin or applies the application’s documented invalidation behavior.
  8. Review Varnish logs and statistics together with the Nginx error log after each topology change. A 502 or timeout usually identifies a failed hop; a valid origin response with unexpected reuse points to cache policy.

No performance or cache-hit percentage can be inferred from the configuration alone. Measure with representative anonymous and authenticated traffic after correctness and privacy checks pass.

Troubleshoot the failures that occur most often

Symptom Likely cause What to check
Nginx fails to reload with an address-in-use error Another server block or Varnish already owns the port Run ss -ltnp; make 443, 80, the Varnish listener, and 8080 distinct
Varnish starts but returns a backend error The VCL backend address or port does not match the origin Check .host and .port, then test the origin locally and inspect Varnish logs
Varnish will not start after a VCL edit VCL syntax or an unsupported directive Read the service journal, restore the last working file, and apply the corrected VCL through the normal reload path
The application redirects HTTPS requests back to HTTP The origin does not know the original scheme Ensure Nginx sends X-Forwarded-Proto https and that the application trusts the controlled proxy
The wrong site or tenant is served The original Host header was lost Set proxy_set_header Host $host and verify the origin’s virtual-host configuration
Private or personalized content appears for another user VCL cached a response that should have bypassed cache Pass requests with authorization, exclude personalized paths, preserve cookies and cache-control, purge affected objects, and review logs
Every request appears to miss The response is intentionally uncacheable, cookies vary it, or VCL passes it Inspect response cache-control, request headers, VCL branches, and application-specific cache markers before changing policy
Certificate changes are not visible Nginx or Varnish is still using the previous certificate in memory Reload the component that terminates TLS using its documented certificate-reload procedure, then repeat the external certificate check

Cache safely around application state

Varnish is not a substitute for application-level authorization. A cache key normally includes the URL and host, but an application may vary content by cookies, authorization, language, device, or other headers. Treat those variations as part of the design.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Pass requests carrying Authorization unless the application has a documented public-token policy.
  • Pass non-GET and non-HEAD methods by default. Do not cache writes.
  • Exclude login, account, admin, cart, checkout, order, preview, and other personalized paths unless their responses are explicitly public.
  • Honor origin Cache-Control, Set-Cookie, and privacy directives. Removing them without an application decision can disclose data.
  • Define how content is invalidated after publishing, editing inventory, changing permissions, or logging out. A cache that serves stale public content may be acceptable; a cache that serves stale authorization is not.

Keep the initial policy narrow. Expand it only after observing real response headers and confirming that two different users receive the same representation for every object you intend to share.

Operational checks after deployment

Record the final listener map, certificate locations, VCL revision, and the owner of each cacheable route. That information makes incident response faster than reconstructing the topology from service files.

  • Monitor Nginx TLS and upstream errors separately from Varnish backend failures.
  • Keep access to the Varnish listener restricted to localhost or a protected internal network.
  • Reload certificates before expiry and verify the public chain from outside the server.
  • After changing DNS for a backend hostname, recompile or reload VCL because DNS is resolved when VCL is compiled.
  • Use application-aware cache headers and logs when deciding whether a request was served from cache.
  • Document which component supports the required HTTP/2 or HTTP/3 edge behavior in the chosen TLS design.

The reliable deployment sequence is therefore: establish unique listeners, make the origin work by itself, compile a conservative VCL, configure one TLS terminator, verify each hop, and only then broaden caching.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.