Bird
Raised Fist0
Nginxdevops~5 mins

FastCGI cache in Nginx - Commands & Configuration

Choose your learning style10 modes available
Introduction
Web servers often need to speed up responses from dynamic applications. FastCGI cache stores responses from these apps so the server can quickly reuse them without running the app again.
When your website uses PHP or another FastCGI application and you want to reduce server load.
When you want faster page loads for visitors by serving cached content.
When you want to reduce the time your backend app spends generating the same content repeatedly.
When you want to handle more users without upgrading hardware by caching responses.
When you want to control how long cached content stays fresh before refreshing.
Config File - nginx.conf
nginx.conf
http {
    fastcgi_cache_path /var/cache/nginx/fastcgi_cache levels=1:2 keys_zone=MYCACHE:10m inactive=60m;
    fastcgi_cache_key "$scheme$request_method$host$request_uri";

    server {
        listen 80;
        server_name example.com;

        location ~ \.php$ {
            include fastcgi_params;
            fastcgi_pass unix:/run/php/php8.1-fpm.sock;

            fastcgi_cache MYCACHE;
            fastcgi_cache_valid 200 302 10m;
            fastcgi_cache_valid 404 1m;
            fastcgi_cache_use_stale error timeout invalid_header http_500;
            fastcgi_cache_min_uses 1;
            add_header X-Cache $upstream_cache_status;
        }
    }
}

fastcgi_cache_path sets where cache files are stored and how much memory is used for keys.

fastcgi_cache_key defines how requests are identified uniquely.

Inside server, the location ~ \.php$ block configures FastCGI caching for PHP files.

fastcgi_cache enables caching using the defined zone.

fastcgi_cache_valid sets how long responses with certain status codes are cached.

fastcgi_cache_use_stale allows serving stale cache if backend errors occur.

add_header X-Cache adds a header to show cache status in responses.

Commands
Check the nginx configuration file syntax to ensure no errors before reloading.
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 FastCGI cache configuration without stopping the server.
Terminal
sudo systemctl reload nginx
Expected OutputExpected
No output (command runs silently)
Make a request to the PHP page and check the response headers to see if caching is working.
Terminal
curl -I http://example.com/index.php
Expected OutputExpected
HTTP/1.1 200 OK Server: nginx Date: Thu, 01 Jun 2023 12:00:00 GMT Content-Type: text/html; charset=UTF-8 X-Cache: MISS
Make the same request again to verify the response is served from cache this time.
Terminal
curl -I http://example.com/index.php
Expected OutputExpected
HTTP/1.1 200 OK Server: nginx Date: Thu, 01 Jun 2023 12:00:05 GMT Content-Type: text/html; charset=UTF-8 X-Cache: HIT
Key Concept

If you remember nothing else from this pattern, remember: FastCGI cache stores dynamic responses on disk so nginx can serve them quickly without running the backend app again.

Common Mistakes
Not testing nginx configuration before reload
Reloading with syntax errors causes nginx to fail and stop serving requests.
Always run 'nginx -t' to check config syntax before reloading.
Not setting a unique fastcgi_cache_key
Cache may serve wrong content for different URLs or request methods.
Include scheme, method, host, and URI in fastcgi_cache_key to uniquely identify requests.
Not adding X-Cache header to verify caching
You cannot easily tell if responses come from cache or backend.
Add 'add_header X-Cache $upstream_cache_status;' to see cache status in response headers.
Summary
Configure fastcgi_cache_path and fastcgi_cache_key in nginx.conf to enable caching.
Use fastcgi_cache and fastcgi_cache_valid inside location blocks to control caching behavior.
Test nginx config syntax with 'nginx -t' before reloading to avoid downtime.
Verify caching works by checking the X-Cache header in HTTP responses.

Practice

(1/5)
1. What is the main purpose of enabling FastCGI cache in nginx?
easy
A. To store dynamic page responses and serve them faster next time
B. To block all dynamic content from being served
C. To increase the size of the nginx log files
D. To disable backend server processing completely

Solution

  1. Step 1: Understand FastCGI cache function

    FastCGI cache stores dynamic content generated by backend servers temporarily.
  2. Step 2: Identify the benefit

    Serving cached content reduces backend load and speeds up response time.
  3. Final Answer:

    To store dynamic page responses and serve them faster next time -> Option A
  4. Quick Check:

    FastCGI cache purpose = store and speed up [OK]
Hint: FastCGI cache speeds up dynamic pages by storing them [OK]
Common Mistakes:
  • Thinking it blocks dynamic content
  • Confusing cache with logging
  • Assuming it disables backend servers
2. Which of the following is the correct syntax to define a FastCGI cache zone in nginx?
easy
A. fastcgi_cache /path/to/cache keys_zone=mycache inactive=60m;
B. fastcgi_cache_zone /path/to/cache keys_zone=mycache:10m inactive=60m;
C. fastcgi_cache_path keys_zone=mycache:10m /path/to/cache inactive=60m;
D. fastcgi_cache_path /path/to/cache levels=1:2 keys_zone=mycache:10m inactive=60m;

Solution

  1. Step 1: Recall fastcgi_cache_path syntax

    The correct syntax includes path, levels, keys_zone with size, and inactive time.
  2. Step 2: Match options with syntax

    fastcgi_cache_path /path/to/cache levels=1:2 keys_zone=mycache:10m inactive=60m; matches the correct order and parameters exactly.
  3. Final Answer:

    fastcgi_cache_path /path/to/cache levels=1:2 keys_zone=mycache:10m inactive=60m; -> Option D
  4. Quick Check:

    Correct fastcgi_cache_path syntax = fastcgi_cache_path /path/to/cache levels=1:2 keys_zone=mycache:10m inactive=60m; [OK]
Hint: Remember: fastcgi_cache_path needs path, levels, keys_zone [OK]
Common Mistakes:
  • Mixing keys_zone and path order
  • Omitting levels parameter
  • Using fastcgi_cache instead of fastcgi_cache_path
3. Given this nginx config snippet:
fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=cache_zone:10m inactive=30m;
server {
location ~ \.php$ {
fastcgi_cache cache_zone;
fastcgi_cache_valid 200 10m;
fastcgi_pass backend;
}
}

What happens when a PHP page is requested twice within 10 minutes?
medium
A. The cache is cleared after the first request
B. Both requests are forwarded to the backend server
C. The second request is served from cache, speeding up response
D. The second request returns a 404 error

Solution

  1. Step 1: Understand fastcgi_cache_valid 200 10m

    This means HTTP 200 responses are cached for 10 minutes.
  2. Step 2: Analyze repeated request behavior

    The first request caches the response; the second request within 10 minutes uses cache.
  3. Final Answer:

    The second request is served from cache, speeding up response -> Option C
  4. Quick Check:

    Cache valid time means reuse cached response [OK]
Hint: fastcgi_cache_valid sets cache duration for status codes [OK]
Common Mistakes:
  • Assuming backend always handles requests
  • Thinking cache clears after first request
  • Confusing cache duration with cache clearing
4. You configured FastCGI cache but notice no caching happens. Which nginx directive is most likely missing?
medium
A. fastcgi_cache_path
B. fastcgi_cache_key
C. fastcgi_cache_valid
D. fastcgi_pass

Solution

  1. Step 1: Identify required directives for caching

    fastcgi_cache_path defines cache storage; fastcgi_cache_valid sets cache time; fastcgi_pass sends requests to backend.
  2. Step 2: Understand fastcgi_cache_key role

    fastcgi_cache_key defines how requests are identified for caching; missing it disables caching.
  3. Final Answer:

    fastcgi_cache_key -> Option B
  4. Quick Check:

    Missing cache key disables caching [OK]
Hint: Without fastcgi_cache_key, nginx can't store cache properly [OK]
Common Mistakes:
  • Forgetting to set fastcgi_cache_key
  • Confusing fastcgi_cache_valid with cache enabling
  • Assuming fastcgi_pass controls caching
5. You want to cache PHP responses but exclude logged-in users identified by a cookie user_session. Which configuration snippet correctly disables cache for logged-in users?
hard
A. fastcgi_no_cache $cookie_user_session;
B. fastcgi_cache_valid 200 10m if_not $cookie_user_session;
C. fastcgi_cache_key $cookie_user_session;
D. fastcgi_cache_bypass $cookie_user_session;

Solution

  1. Step 1: Understand directives controlling cache bypass

    fastcgi_no_cache disables caching when its variable is true; fastcgi_cache_bypass skips cache lookup but may still cache response.
  2. Step 2: Identify correct directive for excluding logged-in users

    fastcgi_no_cache $cookie_user_session; disables caching for requests with that cookie, preventing cached content for logged-in users.
  3. Final Answer:

    fastcgi_no_cache $cookie_user_session; -> Option A
  4. Quick Check:

    fastcgi_no_cache disables caching for matching requests [OK]
Hint: Use fastcgi_no_cache to exclude requests from caching [OK]
Common Mistakes:
  • Using fastcgi_cache_bypass alone to prevent caching
  • Trying to conditionally set fastcgi_cache_valid
  • Misusing fastcgi_cache_key for cache control
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard