NGINX FastCGI Cache on NGINX > Apache > PHP-FPM

Richard1984 asked:

I had failed attempts earlier at getting Nginx Fast-CGI caching to work in Nginx > Apache > PHP-FPM config so I started fresh on a new server but am still having issues.

The server has a clean Ubuntu 16.04 install with Nginx 1.14.2, Apache 2.4.18 and PHP-FPM 5.6 (just for testing sake).

My /etc/nginx/nginx.conf config is stock as I’ve only made changes in vhost (anything outside server block is effectively nginx.conf).

My Nginx vhost config is:

fastcgi_cache_path /etc/nginx/cache levels=1:2 keys_zone=MYAPP:100m inactive=60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
add_header X-Cache $upstream_cache_status;

server {
        listen   80;

        root /var/www/;
        index index.php index.html index.htm;


        location / {
        try_files $uri $uri/ /index.php;

        location ~ \.php$ {

        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;

        fastcgi_cache MYAPP;
        fastcgi_cache_valid 200 60m;

         location ~ /\.ht {
                deny all;

My apache2 is

        DocumentRoot /var/www/
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
        ProxyPassMatch ^/(.*\.php(/.*)?)$ unix:/run/php/php5.6-fpm.sock|fcgi://localhost/var/www/

To test caching, I have following in /var/www/cachetest.php

echo time();

However testing changes every second and consequently /etc/nginx/cache is always empty (its 777 for now).

Any ideas why cache isn’t working?

For testing sake, I want Nginx to cache every dynamic page regardless of cache-headers etc.

P.S. I have to use NGINX > Apache > PHP-FPM for now for htaccess (planning to ditch it in future)

My answer:

You can’t fastcgi_cache because you never fastcgi_pass to PHP-FPM.

In nginx, the cache is attached to a specific method of sending requests upstream, e.g. fastcgi, proxy, uwsgi, etc.

You can either use a proxy_cache instead, or better yet, just fastcgi_pass to PHP-FPM directly from nginx, and get rid of Apache as it’s redundant.

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.