Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk8 min

How to Add Expires Headers in Nginx for Browser Caching

Configure Nginx browser caching with the expires directive. This guide covers static-file locations, cache lifetimes, versioned filenames, variable maps, immutable policies, verification, and troubleshooting.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Add an expires directive to the Nginx location that serves your static files, test the configuration, reload Nginx, and verify the response with curl -I. For example, expires 7d; tells clients to reuse a successful static-file response for seven days. If your asset filenames change whenever their contents change, a longer policy such as expires 1y; can reduce repeat downloads without leaving old files permanently associated with a URL.

The directive writes both an Expires header and a Cache-Control: max-age=... header. It is intended for browser and downstream-cache behavior; it does not by itself configure Nginx’s separate proxy-cache storage.

As an Amazon Associate I earn from qualifying purchases.

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.

What the Nginx expires directive does

Nginx’s expires directive, provided by the ngx_http_headers_module, tells a browser or intermediary how long it may reuse a response without fetching the same URL again. A positive duration produces a Cache-Control header with a corresponding max-age value and an Expires date calculated from the response time.

For a seven-day policy, the response will contain the equivalent of Cache-Control: max-age=604800 (seven days expressed in seconds) and an Expires date in the future. The exact date is generated by Nginx when it sends the response.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Where it is valid

You can place expires in the http, server, or location context, or in an if block inside a location. The default is off, which leaves existing Expires and Cache-Control headers unchanged.

Which responses it affects

The directive applies only to these response statuses: 200, 201, 204, 206, 301, 302, 303, 304, 307, and 308. An error response or another status outside that list is not given an expiry policy by this directive.

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.

Choose the files and lifetime before editing Nginx

Set caching where the URL represents a reusable static object, such as a stylesheet, JavaScript file, image, font, or downloadable document. Do not apply a long lifetime to an HTML route or an API response merely because it is delivered by the same server block; those URLs often need to reflect changes quickly.

Use a short or moderate lifetime for stable URLs

A policy such as expires 7d; is a practical starting point when the same filename may be replaced during the week. Visitors can still receive a newer file after the lifetime ends, while repeat visits during that period can use the cached copy.

Use a long lifetime only with cache-busting filenames

If a deployment changes the filename whenever the contents change—for example, by producing a new versioned asset name—expires 1y; can be appropriate. The old URL can remain cached for its full lifetime while new pages reference a new URL. Without that filename change, a year-long policy can keep an updated file from being requested until the cached lifetime expires.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Decide whether zero or negative values are intentional

A zero duration emits Cache-Control: max-age=0. A negative duration emits Cache-Control: no-cache. These are useful when clients should check with the origin rather than treating the response as freely reusable, but they are not equivalent to removing all cache-related headers.

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

Basic static-file configuration

Put the directive in a location that actually handles the static extensions you want to cache. This example covers common assets and assigns a seven-day lifetime:

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

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

The regular expression is case-insensitive because of ~*, so an uppercase extension is matched as well. Adjust the extension list to your application rather than copying it unchanged. A document that should be retained for one year could use a separate, more specific location:

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

Keep the policy in the location that serves the files. A server-level directive can be useful for a broad default, but a more specific location may override it, and a misplaced directive can make verification appear to fail.

Apply the change safely

  1. Find the active configuration. Identify the server block that serves the hostname and the location that handles the target files. Distribution packages commonly include a main configuration plus files included from a conf.d or sites directory; use the layout used by your installation rather than assuming a single path.
  2. Add the directive to the matching location. Start with a limited extension set and a lifetime such as 7d. Keep unrelated application routes outside that block.
  3. Check syntax before reloading. Run nginx -t with the same privileges and configuration that your service uses. Correct any reported file, brace, or directive errors before continuing.
  4. Reload Nginx. Use your service manager’s reload operation, such as systemctl reload nginx, so existing connections are not needlessly terminated. If your installation uses a different service manager, use its equivalent reload action.
  5. Inspect the actual response. Request the exact public URL, not a local filesystem path: curl -I https://example.com/assets/site.css. Look for a Cache-Control: max-age=... value matching the selected duration and an Expires date that is in the future.
  6. Test a representative status and location. Check more than one extension if several regex locations exist. Also test through the public hostname and protocol that visitors use, because another proxy or virtual host can change the response you see.

Syntax and value behavior

The directive has two forms:

expires [modified] time;
expires epoch | max | off;
Value Headers and meaning When to use it
time greater than zero Sets Cache-Control: max-age=t, where t is the duration in seconds, and calculates an Expires date from the response time. Normal browser caching for assets with a known replacement window, such as 7d or 1y.
0 Sets max-age=0. When a client should not consider the response fresh without checking.
Negative time Sets Cache-Control: no-cache. When revalidation is required rather than unrestricted reuse.
modified time Computes expiry from the file’s modification time plus the specified duration, rather than from the request time. Policies tied to the on-disk file timestamp.
@15h30m Uses a time-of-day expiry. The @ form is supported in Nginx versions since 0.7.9 and 0.6.34. When all responses should expire at a particular daily clock time.
max Sets Expires to 31 December 2037 at 23:55:55 GMT and sets Cache-Control: max-age=315360000, or ten years. Only when the URL is effectively permanent, normally because its name is content-versioned.
epoch Sets Expires to 1 January 1970 at 00:00:01 GMT and Cache-Control: no-cache. An explicit stale-by-design policy.
off Leaves Expires and Cache-Control unchanged. This is the default. When another configuration layer already supplies the desired headers.

The modified form changes the reference point only; it does not turn a dynamic response into a file-based response. Use it where the served file’s modification time is the value you want to anchor.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Set different lifetimes with a variable

Since Nginx 1.7.9, the value may be a variable. A map in the http context lets you select a policy from a response property. This pattern gives PDFs 42 days, images the max policy, and everything else no expires change:

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

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

        location / {
            expires $expires;
        }
    }
}

The map’s keys must match the value available at the point where the variable is evaluated. If a response has a content type that does not match either entry, default off leaves the existing headers alone. Test each category with curl -I; a variable-driven policy is harder to diagnose than a single literal duration.

When you need immutable

The expires directive cannot emit the immutable cache-control token. If your policy specifically requires that token, use an explicit header instead, for example:

location ~* .(?:css|js)$ {
    add_header Cache-Control "public, max-age=31536000, immutable" always;
}

Choose either the expires policy or this custom Cache-Control policy for a location. Do not combine expires with a custom Cache-Control add_header in the same location: the response can contain duplicate or contradictory cache instructions. The one-year value above is a policy choice, not a requirement; use it only when the URL changes whenever the file changes.

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

Location matching can silently defeat the setting

Nginx selects one location to process a request. With overlapping regular-expression locations, it uses the first matching regex location it reaches. For example, if one regex matches .css and another earlier regex matches both .css and .js, the later block containing expires may never handle the CSS request.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Keep related extensions in one regex where practical, or order regex locations deliberately. When a header is missing, inspect the complete active configuration and identify the selected location rather than adding another overlapping block. A server-level setting can also be hidden by a more specific location that supplies its own headers.

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

Browser caching is separate from Nginx proxy caching

expires controls what the client and downstream caches are told to store. Nginx’s own proxy cache is a separate feature with its own cache zone, key, validity, and storage behavior. The origin’s Expires and Cache-Control headers can influence proxy behavior, but the exact result depends on the proxy-cache configuration and was not established by the directive alone.

If a response looks correct at the origin but a reverse proxy serves a different policy, inspect that proxy’s configuration and headers independently. Do not assume that adding expires automatically enables, fills, or purges Nginx’s proxy cache.

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

Verify headers and diagnose common failures

No Cache-Control or Expires header appears

  • Confirm the requested URL maps to the location containing expires.
  • Check for an earlier matching regular-expression location.
  • Run nginx -t and reload the instance whose configuration serves the hostname.
  • Check that the response status is one of the statuses supported by the directive.
  • Look for another configuration layer that replaces or hides the header.

The duration is not the one you configured

  • Convert the configured duration to seconds and compare it with max-age. For example, seven days is 604800 seconds.
  • Check whether a variable or map selects a different value.
  • Inspect whether a more specific location handles the file.
  • Make sure you are not viewing a response from a downstream proxy or an already cached browser entry.

Two cache policies appear in the response

Search the active configuration for both expires and add_header Cache-Control in the same request path. Remove the conflicting directive or consolidate the policy so one location emits one intentional cache instruction.

The date appears unexpectedly old or far in the future

Check whether the configuration uses modified, max, or epoch rather than an ordinary duration. modified anchors the calculation to the file timestamp; max deliberately uses the fixed 2037 date and ten-year max-age; epoch deliberately produces a 1970 date and no-cache.

Operational patterns that avoid stale deployments

Pattern 1: replaceable static filenames

Use a moderate duration such as 7d for assets whose URL stays the same while contents may be replaced. This limits how long an unchanged URL can remain fresh and reduces the chance that a routine deployment waits a full year to become visible to every browser.

Pattern 2: versioned filenames

Use a long duration such as 1y or the max value only when the deployment process creates a new URL for every content change. New pages then point at the new filename, while old cached objects remain associated with their old URLs.

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

Pattern 3: type-based policies

Use a map when a single server handles several file types with different retention needs. Keep the default as off until each type has an intentional policy, then verify one URL from every mapped category.

Rollback and change control

  1. Keep the previous configuration block available while you evaluate the new headers.
  2. If verification reveals an unintended policy, restore the prior expires value or remove the directive, run nginx -t, and reload.
  3. Remember that a browser or intermediary may already have stored a response under the old lifetime. Changing the server header cannot force an already-fresh object to be discarded; use a new asset URL when an immediate content change is required.

A reliable implementation is therefore narrow and explicit: match only the static URLs you intend to cache, choose a lifetime that fits how those URLs change, avoid competing header directives, and verify the live response after every configuration change.

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 from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.