1

I am using fastcgi caching, and would like to specify which URLs the cache should be active on.

I use a rewrite rule to determine which controller file to access, and set any query parameters dynamically

I want to specify URLs in which the cache is activated, and those in which it is inactive, this is my code:

server {
    listen 80;
    server_name domain.com;
    root /home/site/wwwroot;

    set %skip_cache 1;        #this is the variable that I want to set to 0 on specific URLS

    location / {
        try_files $uri $uri/ $uri.html @php;
    }
    location @php {         
        rewrite ^(/[^/]+)$ $1.php last;
        rewrite ^(/[^/]+)/(.*)$ $1.php?q=$2 last;
    }


    location /user/ {
        set $skip_cache 0;
    }

    location /objects/ {
        set $skip_cache 0;
    }

    location ~ \.php$  {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        fastcgi_split_path_info ^(.+?\.php)(/.*)?$;
        fastcgi_connect_timeout         300; 
        ...etc...

    #cache parameters
    fastcgi_param FASTCGI_CACHE 1;
    fastcgi_cache cfcache;
    fastcgi_cache_valid 30s;
    fastcgi_cache_bypass $skip_cache;
    fastcgi_no_cache $skip_cache;
    add_header X-FastCGI-Cache $upstream_cache_status;  
}

as you can see, the variable $skip_cache is set to 1 by default, and I would like to white list URLs for caching.

An example I would like cached is domain.com, domain.com/user/123 and domain.com/objects/456

Currently, if I browse to /user/123, the result is a 404 error, as I believe that location block with the variable setting is being used exclusively.

1 Answer 1

1

If you want to set a variable based on the original request, you should use a map directive with the $request_uri variable. See this document for details.

For example:

map $request_uri $skip_cache {
    default      1;
    ~^/user/     0;
    ~^/objects/  0;
}
server {
    ...
    fastcgi_cache_bypass $skip_cache;
    fastcgi_no_cache $skip_cache;
    ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that's working great! Do you know how to make it hit the index file as well, so for example domain.com which is rewritten to domain.com/index.php how to get that index file to also be white listed?
You can add a / 0; line and a ~^/index.php 0; line to the map.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.