When running page speed insights, it seems that TTFB (Time To First Byte) is something that it really doesn’t like when checking performance.
To solve this, we can use nginx’s caching of compiled PHP pages. Even better, the cache can be a RAM disk, making it very responsive.
First, create a directory for the RAM disk:
sudo mkdir -p /mnt/nginx-cache
Now create an entry in the fstab file so it’s mounted to the RAM disk on boot:
sudo nano /etc/fstab
tmpfs /mnt/nginx-cache tmpfs rw,size=2048M 0 0
This creates a 2GB RAM disk. Edit the size as appropriate for your server. Then mount it:
sudo mount /mnt/nginx-cache
Now, create a cache configuration file for Nginx:
sudo nano /etc/nginx/conf.d/cache.conf
fastcgi_cache_path /etc/nginx-cache levels=1:2 keys_zone=phpcache:512m inactive=2h max_size=1024m; fastcgi_cache_key "$scheme$request_method$host$request_uri";
This creates a cache of 1GB with a default time of 2 hours. Next update the config files for your website – change your config file name where appropriate.
/etc/nginx/sites-enabled/mysite.conf
Inside of the location ~ "^(.+\.php)($|/)" {
section, add:
# ---------------------------------------------- # Caching # ---------------------------------------------- # This defines which cache to use (defined in /etc/nginx/cache.conf) fastcgi_cache phpcache; # Cache only 200 Okay responses for 2 hours fastcgi_cache_valid 200 2h; # Don't cache POST requests, only GET fastcgi_cache_methods GET HEAD; # Optional. Add a header to prove it works add_header X-Fastcgi-Cache $upstream_cache_status;
now you should be able to restart nginx sudo service nginx restart
and access the site via a web browser. Then you can use something like developer tools access the headers of the web requests. You should find a header:
X-Fastcgi-Cache: HIT