I'm new to Nginx and Wordpress as a combo. I would love a sanity check on this server side caching code.
Specifically
- Is the sequencing correct - esp. the location statements?
- Is there anything redundant or critically missing?
- If I wanted to set a different cache time for say .mp4 and png - eg 1d, not 1w, how would I do so?
Many thanks for your help.
fastcgi_cache_path /etc/nginx/cache levels=1:2 keys_zone=wpcache:200m max_size=2g inactive=1w use_temp_path=off;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
#INFO=name=WordPress (FastCGI Cache)
set $skip_cache 0;
# POST requests and urls with a query string should always go to PHP
if ($request_method = POST) {
set $skip_cache 1;
}
if ($query_string != "") {
set $skip_cache 1;
}
# Don't cache uris containing the following segments
if ($request_uri ~* "${template_location}wp-admin/|${template_location}xmlrpc.php|${template_location}wp-.*.php|${template_location}feed/|${template_location}index.php|${template_location}sitemap(_index)?.xml") {
set $skip_cache 1;
}
# Don't use the cache for logged in users or recent commenters
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_no_cache|wordpress_logged_in") {
set $skip_cache 1;
}
location / {
index index.php index.html index.htm;
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
include snippets/fastcgi-php.conf;
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_lock on;
fastcgi_cache_bypass $skip_cache;
fastcgi_no_cache $skip_cache;
add_header X-FastCGI-Cache $upstream_cache_status;
}
location ~* ^.+.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|js|jpg|jpeg
|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi
|wav|bmp|rtf)$ {
access_log off;
log_not_found off;
expires max;
}
location = /robots.txt {
access_log off;
log_not_found off;
}
location ~ /. {
deny all;
access_log off;
log_not_found off;
}
location ~ /purge(/.*) {
fastcgi_cache_purge FASTCGICACHE "$scheme$request_method$host$1";
}
# Wordpress Permalinks
location / {
try_files $uri $uri/ /index.php?$args;
}