Bird
Raised Fist0
Nginxdevops~5 mins

Expires directive in Nginx - Commands & Configuration

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Websites often serve files like images, scripts, and stylesheets. The Expires directive helps tell browsers how long to keep these files before asking the server for new ones. This speeds up page loading and reduces server work.
When you want browsers to cache images so they load faster on repeat visits.
When you serve static files like CSS or JavaScript that rarely change.
When you want to reduce bandwidth by avoiding repeated downloads of the same files.
When you want to improve your website's speed and user experience.
When you want to control how long browsers keep files before checking for updates.
Config File - nginx.conf
nginx.conf
http {
    server {
        listen 80;
        server_name example.com;

        location /images/ {
            expires 30d;
        }

        location /css/ {
            expires 7d;
        }

        location /js/ {
            expires 1h;
        }
    }
}

This configuration sets caching times for different file types.

  • location /images/: Images are cached for 30 days.
  • location /css/: CSS files are cached for 7 days.
  • location /js/: JavaScript files are cached for 1 hour.

The expires directive tells browsers how long to keep these files before asking the server again.

Commands
Check the nginx configuration file for syntax errors before applying changes.
Terminal
sudo nginx -t
Expected OutputExpected
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Reload nginx to apply the new configuration without stopping the server.
Terminal
sudo systemctl reload nginx
Expected OutputExpected
No output (command runs silently)
Request headers for an image file to verify the Expires header is set correctly.
Terminal
curl -I http://example.com/images/sample.jpg
Expected OutputExpected
HTTP/1.1 200 OK Server: nginx Date: Wed, 05 Jun 2024 12:00:00 GMT Content-Type: image/jpeg Expires: Fri, 05 Jul 2024 12:00:00 GMT Cache-Control: max-age=2592000
Key Concept

If you remember nothing else from this pattern, remember: the Expires directive tells browsers how long to keep files before checking for updates, speeding up your website.

Common Mistakes
Setting expires time too short or too long without considering file update frequency.
If too short, browsers request files too often, slowing down the site. If too long, users may see outdated files.
Set expires times based on how often files change; longer for rarely changed files, shorter for frequently updated ones.
Not testing nginx configuration before reload.
Syntax errors can cause nginx to fail to reload, making the site unavailable.
Always run 'sudo nginx -t' to check config syntax before reloading.
Summary
Use the Expires directive in nginx to control browser caching times for different file types.
Check nginx configuration syntax with 'nginx -t' before reloading to avoid errors.
Reload nginx to apply changes and verify caching headers with curl.

Practice

(1/5)
1. What is the main purpose of the expires directive in an nginx configuration?
easy
A. To specify the file upload size limit
B. To control how long browsers cache files before requesting them again
C. To limit the number of simultaneous connections
D. To set the server's time zone

Solution

  1. Step 1: Understand the role of expires in nginx

    The expires directive tells browsers how long to keep files cached before checking for updates.
  2. Step 2: Compare options with this function

    Only To control how long browsers cache files before requesting them again matches this purpose; others relate to different server settings.
  3. Final Answer:

    To control how long browsers cache files before requesting them again -> Option B
  4. Quick Check:

    Expires directive = browser cache time [OK]
Hint: Expires controls browser cache duration for files [OK]
Common Mistakes:
  • Confusing expires with server timezone settings
  • Thinking expires limits connections
  • Mixing expires with upload size limits
2. Which of the following is the correct syntax to set the expires directive to 1 day in nginx?
easy
A. expires = 1 day;
B. expires 1 day
C. expires 24hours;
D. expires 1d;

Solution

  1. Step 1: Recall nginx expires syntax

    The correct syntax uses a time value followed by a semicolon, e.g., expires 1d; for one day.
  2. Step 2: Check each option for syntax correctness

    expires = 1 day; uses invalid '=' and full word 'day'; expires 1 day lacks semicolon; expires 24hours; uses invalid time unit '24hours'. Only B matches correct syntax: expires 1d;.
  3. Final Answer:

    expires 1d; -> Option D
  4. Quick Check:

    Correct syntax ends with semicolon and uses short time unit [OK]
Hint: Use short time units with semicolon, like 'expires 1d;' [OK]
Common Mistakes:
  • Omitting semicolon at the end
  • Using spaces in time value
  • Writing full words like 'day' instead of 'd'
3. Given this nginx config snippet:
location ~* \.(jpg|jpeg|png)$ {
  expires 30d;
}

What will the browser do when accessing a PNG file?
medium
A. Cache the PNG file for 30 seconds
B. Never cache the PNG file
C. Cache the PNG file for 30 days before re-requesting
D. Immediately re-request the PNG file every time

Solution

  1. Step 1: Analyze the regex and expires directive

    The location matches .jpg, .jpeg, and .png files and sets expires 30d;, meaning 30 days caching.
  2. Step 2: Understand browser caching behavior

    Browsers will keep the PNG file cached for 30 days before checking for updates.
  3. Final Answer:

    Cache the PNG file for 30 days before re-requesting -> Option C
  4. Quick Check:

    Expires 30d means 30 days cache [OK]
Hint: Regex matches file types; expires sets cache time [OK]
Common Mistakes:
  • Confusing days with seconds
  • Ignoring regex file matching
  • Assuming no caching without explicit 'no-cache'
4. Identify the error in this nginx config:
location /static/ {
  expires 10days;
}
medium
A. The time unit '10days' is invalid; should be '10d'
B. Missing semicolon after expires directive
C. Location block syntax is incorrect
D. Expires directive cannot be used inside location

Solution

  1. Step 1: Check the expires time unit

    The correct time unit uses short forms like 'd' for days. '10days' is invalid syntax.
  2. Step 2: Verify other syntax elements

    Semicolon is present, location syntax is correct, and expires can be used inside location.
  3. Final Answer:

    The time unit '10days' is invalid; should be '10d' -> Option A
  4. Quick Check:

    Use short time units like 'd' not full words [OK]
Hint: Use short units like 'd' for days, not full words [OK]
Common Mistakes:
  • Writing full words for time units
  • Forgetting semicolon (not the case here)
  • Thinking expires can't be in location block
5. You want to set caching so that CSS files are cached for 7 days, but HTML files are never cached. Which nginx config snippet achieves this?
hard
A. location ~* \.css$ { expires 7d; } location ~* \.html$ { expires -1; }
B. location ~* \.css$ { expires 7d; } location ~* \.html$ { expires 0; }
C. location ~* \.css$ { expires 7d; } location ~* \.html$ { expires off; }
D. location ~* \.css$ { expires 7d; } location ~* \.html$ { expires never; }

Solution

  1. Step 1: Recall how to disable caching in nginx

    Setting expires -1; disables caching (forces no cache) for files.
  2. Step 2: Check each option for correct disables and enables

    location ~* \.css$ { expires 7d; } location ~* \.html$ { expires -1; } uses expires 7d; for CSS and expires -1; for HTML, which is correct. Others use invalid or incorrect values.
  3. Final Answer:

    location ~* \.css$ { expires 7d; } location ~* \.html$ { expires -1; } -> Option A
  4. Quick Check:

    Use 'expires -1;' to disable caching [OK]
Hint: Use 'expires -1;' to disable caching for files [OK]
Common Mistakes:
  • Using 'expires off;' which is invalid
  • Using 'expires 0;' which sets immediate expiry but not no-cache
  • Using 'expires never;' which is not valid syntax