nginxcachingnginx-configcache-controlnginx-cache

Nginx cache not working for certain URL's


I have some wordpress websites running. Nginx fcgi_cache is working for all of these websites but one!

This particular one is no different than others. But some of this site's URLs are not caching!

The cache status header always gives: MISS

This is my nginx configuration for cache:

if ($request_method = POST) { set $skip_cache 1; }
if ($query_string != "") { set $skip_cache 1; }
if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|^/feed/*|/tag/.*/feed/*|/.*sitemap.*\.(xml|xsl)") { set $skip_cache 1; }
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") { set $skip_cache 1; }

fastcgi_cache_key "$host$request_uri";
fastcgi_cache wpcache;
fastcgi_cache_valid 200 301 302 2h;
fastcgi_cache_use_stale error timeout updating invalid_header http_500 http_503;
fastcgi_cache_min_uses 1;
fastcgi_cache_bypass $skip_cache;
fastcgi_ignore_headers Cache-Control Expires;
add_header X-Cache $upstream_cache_status;

Notice: I checked $skip_cache is 0 and it's not because of bypass

What's the problem of my config? And how can I make nginx cache these URL's too?


Solution

  • The Cookies

    problem was because of a plugin which used cookies and set a cookie on every page. There is a solution to that issue.

    Ignore Set-Cookie header:

    fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
    

    This will prevent nginx from bypassing the pages with Set-Cookie header.

    Note: Since you a line of code to bypass wp-admin and a line of code for wordpress cookies, There is no need to worry about necessary cookies...

    if ($request_uri ~* "/wp-admin/|/xmlrpc.php|wp-.*.php|^/feed/*|/tag/.*/feed/*|/.*sitemap.*\.(xml|xsl)") { set $skip_cache 1; }
    if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") { set $skip_cache 1; }