DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
VGSources
Blog

How to Add Expires Headers in Nginx for Browser Caching

Configure Nginx browser caching correctly with the expires directive, including static-asset examples, long-lived fingerprinted files, variable policies, immutable headers, location pitfalls, and curl verification.
WorldNginx for Browser Caching Length10 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Put an expires directive in the Nginx location that serves your static files, then reload Nginx and verify the response with curl. For example, expires 7d; makes Nginx send Cache-Control: max-age=604800 and an Expires date seven days ahead. Use a long lifetime such as 1y only for filenames that change whenever their contents change (for example, hashed JavaScript, CSS, image, or font files).

What the Nginx expires directive does

Nginx’s expires directive, provided by ngx_http_headers_module, adds or changes two response headers:

As an Amazon Associate I earn from qualifying purchases.

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.
  • Expires, an HTTP date after which a stored response is considered stale.
  • Cache-Control: max-age=..., the lifetime in seconds for which a browser or downstream cache may reuse the response.

The directive affects client-side caching. It does not, by itself, create an Nginx proxy cache or decide whether your application regenerates a response. Nginx sends these headers only for responses with status 200, 201, 204, 206, 301, 302, 303, 304, 307, or 308.

Its default is off, which leaves existing Expires and Cache-Control headers unchanged. The directive is valid in the http, server, and location contexts, and in an if block inside location.

#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.

Choose a cache policy before changing Nginx

The correct lifetime depends on whether an old file can safely remain in a player’s browser after you deploy an update.

Asset or response Typical policy Reason
Versioned or fingerprinted CSS, JavaScript, images, fonts expires 1y; or a one-year equivalent The URL changes when the file changes, so an old cached URL does not hide the new release.
Static files without URL versioning expires 7d; or another short, deliberate period Visitors receive updates without waiting a full year for a stale file to expire.
Frequently changing HTML or API output Usually expires off;, or a separate validation policy Long freshness can serve obsolete page data or game-service state.
Responses that must be revalidated A negative value, such as expires -1; Nginx emits Cache-Control: no-cache.

For a one-year policy, Nginx calculates max-age=31536000. A seven-day policy becomes max-age=604800. These values describe freshness; they do not guarantee that a browser will retain a file for the entire period, because users and storage pressure can clear caches earlier.

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

Basic configuration for static files

1. Open the server configuration

Find the server block that serves the site, or the included file containing its static-file location. Put the directive in the narrowest location that matches the assets you intend to cache. A typical block is:

server {
    listen 443 ssl;
    server_name example.com;
    root /var/www/example;

    location ~* .(?:css|js|mjs|png|jpg|jpeg|gif|svg|webp|woff2?)$ {
        expires 7d;
    }
}

The case-insensitive regular expression (~*) matches the listed extensions regardless of capitalization. Adjust the list to your actual files; do not include an extension merely because it is common if that response contains private or rapidly changing data.

2. Use a longer lifetime with fingerprinted filenames

If your build produces names such as app.84f31c.js or styles-2026-10.css, the URL itself identifies the version. That is the situation in which a long cache lifetime is normally safe:

location ~* .(?:css|js|mjs|png|jpg|jpeg|gif|svg|webp|woff2?)$ {
    expires 1y;
}

When a file changes, publish a new filename and update the HTML or manifest that references it. Do not overwrite a long-lived URL and expect every existing browser to fetch the replacement immediately.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

3. Keep dynamic content separate

Do not place a long expires value on a broad location / unless every response under that path has the same caching requirements. Keep HTML, login pages, account data, and game-service endpoints in locations where their own policy is explicit. If no policy is set there, the directive remains off.

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

4. Check and reload safely

After saving the configuration, validate its syntax before reloading:

sudo nginx -t

Only if the test reports a successful configuration should you reload:

sudo systemctl reload nginx

A reload applies the new configuration without stopping existing worker processes. If the syntax test fails, fix the reported file and line instead of reloading a known-bad configuration.

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

How each expires value behaves

Positive and zero durations

For a positive or zero duration, Nginx sends Cache-Control: max-age=t, where t is the duration in seconds, and calculates a matching Expires date from the response time. Examples include:

expires 0;       # immediately stale freshness lifetime
expires 10m;     # 600 seconds
expires 7d;      # 604800 seconds
expires 1y;      # 31536000 seconds

Use 0 when you specifically need an immediately stale response while still emitting the headers. For a revalidation policy, a negative value is clearer because it produces Cache-Control: no-cache.

Negative durations

Any negative time causes Nginx to emit Cache-Control: no-cache. For example:

location = /news.json {
    expires -1;
}

no-cache does not mean “never store.” It tells a cache to validate the stored response before reusing it. If your requirement is that sensitive data not be stored at all, use an explicit policy suited to that response and verify the resulting headers rather than assuming a negative expires value expresses every privacy requirement.

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)

The modified parameter

With modified, Nginx calculates expiration from the file’s modification time plus the supplied duration instead of from the request time:

location ~* .(?:css|js|png|jpg|svg)$ {
    expires modified 7d;
}

This can make the effective lifetime shorter or longer depending on when the file was last changed. It is useful when the file’s modification timestamp is part of your deployment model, but it is less predictable than URL fingerprinting when files are copied between servers or restored from backups.

Time-of-day expiration with @

The @ form sets expiration relative to a time of day, such as:

expires @15h30m;

This form is supported in Nginx versions that include the feature (since 0.7.9 / 0.6.34). Because the resulting lifetime changes throughout the day, document the intended timezone and test around the boundary if you use it.

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

max, epoch, and off

Value Headers Nginx emits Use carefully when
max Expires: 31 Dec 2037 23:55:55 GMT and Cache-Control: max-age=315360000 (ten years) The URL is permanently versioned and you are prepared to keep old files available.
epoch Expires: 1 Jan 1970 00:00:01 GMT and Cache-Control: no-cache You want an explicitly expired date and revalidation behavior.
off Leaves existing headers unchanged; this is the default You are allowing an upstream application or another Nginx directive to control caching.

The max value is a ten-year policy, not an instruction to cache forever. The fixed 2037 date is part of Nginx’s directive behavior. The epoch value uses a 1970 date; a claim that it produces a 2037 date is incorrect.

Use a map when different file types need different lifetimes

Since Nginx 1.7.9, the value can be a variable. A map belongs in the http context, not inside a server or location block. This example assigns PDFs 42 days, images the max policy, and everything else off:

http {
    map $sent_http_content_type $asset_expiry {
        default         off;
        application/pdf 42d;
        ~^image/        max;
    }

    server {
        listen 443 ssl;
        server_name example.com;
        root /var/www/example;

        location /downloads/ {
            expires $asset_expiry;
        }
    }
}

The map key must match what is available at the point Nginx evaluates it. If the map does not select the value you expect, inspect the response’s content type and simplify the match before introducing more rules. A variable makes policy centralized, but it also makes testing each branch essential.

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

When you need immutable, use Cache-Control instead

The expires directive cannot emit the immutable cache-control token. For fingerprinted assets where you want that explicit policy, use add_header instead:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
location ~* .(?:css|js|mjs|png|jpg|jpeg|gif|svg|webp|woff2?)$ {
    add_header Cache-Control "public, max-age=31536000, immutable" always;
}

Do not combine this with an expires directive in the same location. Doing so can produce duplicate or contradictory Cache-Control instructions. Choose one header strategy for that location, and check the final response rather than assuming inheritance has produced the intended result. The always parameter makes the header apply across response statuses where add_header permits it; it does not change the meaning of max-age or make an unsafe URL versioned.

Location matching can decide whether expires applies

Nginx does not merge every matching regular-expression location. When multiple regex locations match a request, Nginx uses the first matching regex location in configuration order. Consequently, this arrangement can silently bypass the intended seven-day policy:

location ~* .(?:css|js)$ {
    expires off;
}

location ~* .(?:css|js|png|jpg)$ {
    expires 7d;
}

A request for app.js matches the first regex and receives expires off. Put the more specific rule first, combine overlapping extensions into one location, or remove the competing rule. Also check exact-match locations (location = ...), prefix locations, and nested configuration when a header appears to be missing.

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

Verify the actual response

Inspect headers with curl

Request headers without downloading the file:

curl -I https://example.com/assets/app.84f31c.js

For expires 7d;, look for a future Expires date and a line resembling:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Cache-Control: max-age=604800

The response status must be one of the statuses supported by the directive. A redirect, conditional request, or error can therefore produce a different header set than the successful static-file request you intended to test.

Test the exact host, path, and scheme

Test the public HTTPS URL, not only an internal upstream address. Virtual hosts, TLS termination, a CDN, or another reverse proxy can select a different configuration. If the site redirects HTTP to HTTPS, follow the redirect separately and inspect the final asset URL:

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.
curl -I http://example.com/assets/app.84f31c.js
curl -I https://example.com/assets/app.84f31c.js

Compare the requested path with the regex, including the filename extension and capitalization. A query string does not change the extension match, but a route such as /asset?id=app.js is not the same as a file named app.js.

Check what the browser received

In browser developer tools, open the Network panel, reload the page, select the asset, and inspect the response headers. A memory-cache or disk-cache result means the browser reused an existing copy; it does not prove that the current server configuration is correct. Use a new filename or clear the browser cache when testing a policy change that affects an already cached URL.

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

Troubleshoot missing or contradictory headers

No Expires or Cache-Control header appears

  • Confirm that the request reached the server block you edited by checking the hostname and port.
  • Confirm that the response status is in the directive’s supported list.
  • Check for an earlier matching regex or exact location.
  • Search included configuration files for another expires, add_header, or proxy layer that changes the response.
  • Run sudo nginx -T to print the complete loaded configuration and locate the rule Nginx is actually using.

The header has the wrong lifetime

  • Convert the configured duration to seconds and compare it with max-age; for example, seven days is 604800.
  • If you used modified, inspect the file’s modification timestamp; the expiration is not measured from the request time.
  • If you used a variable, verify every map branch and the value selected for the response.
  • Check whether a CDN or another reverse proxy is replacing the origin headers before they reach the browser.

Two Cache-Control headers are present

Look for an add_header Cache-Control alongside expires in the same effective location or an upstream service. Remove the duplicate policy or make one layer authoritative. A browser should not have to reconcile two independently chosen freshness lifetimes.

New deployments still show old assets

A long freshness lifetime is doing exactly what it was instructed to do if the URL did not change. Rename the asset with a new content hash or version, update the HTML or manifest reference, and retain the old file while clients transition. Shortening expires on the server cannot retroactively make an already cached response stale before its previously advertised lifetime ends.

Browser caching versus Nginx’s proxy cache

expires primarily tells a browser or downstream cache how long to reuse the response. Nginx’s own proxy-cache feature is a separate mechanism with its own cache-path, key, bypass, and revalidation rules. If Nginx is also acting as a reverse proxy, test both hops: inspect the origin response, then inspect the public response. Do not assume that changing a browser-facing header automatically changes every object already stored in an Nginx proxy cache, or that a proxy cache will ignore the origin’s cache instructions. The effective behavior depends on the proxy-cache configuration and the headers it honors or overrides.

A practical policy for a game site

For a game guide, patch-notes page, or web-based game shell, separate immutable build assets from content that changes independently:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Generate content-hashed names for JavaScript, CSS, fonts, and images produced by the build.
  2. Serve those hashed files from a dedicated location with either expires 1y; or an explicit Cache-Control: public, max-age=31536000, immutable policy. Do not use both.
  3. Serve HTML, manifests that retain a stable URL, account pages, and API responses from separate locations with a short or validation-oriented policy.
  4. Deploy the new HTML or manifest first or atomically with its new asset references, and keep old hashed files available long enough for bookmarked or offline pages to request them.
  5. After deployment, test a new asset URL and an unchanged asset URL with curl -I, then confirm the browser’s Network panel shows the expected headers.

This arrangement lets browsers reuse large, rarely changing assets while allowing the document that points to them to update promptly.

Configuration checklist

  • Choose a lifetime based on whether the URL changes when content changes.
  • Place expires in the matching location, not indiscriminately on every response.
  • Check regex-location order for overlaps.
  • Do not combine expires with a custom Cache-Control header in the same location.
  • Use add_header when the policy specifically requires immutable.
  • Run nginx -t before every reload.
  • Verify the public URL with curl -I and inspect both Cache-Control and Expires.
  • Remember that a changed server policy cannot instantly invalidate a URL already cached under an older policy; version the URL when immediate replacement matters.

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.

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
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

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.