Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

zoidq's avatar
Level 7

Caching with nginx try_files

Hello!

I have some very simple Middleware which saves the rendered output of a page to a static html file. This is done in a similar way to how laravel.com caches pages for those who have watched the Reading Code Laracast series.

I output filename uses the url with / replaced by -

So when I visit: https://site.com/some/page

This file is created: /www/site.com/cache/some-page.html

After messing around and googling for an hour, I've been unable to figure out how to get nginx to check for the existence of this file at that url before proceeding to load the laravel app.

Does anyone know how I can achieve the above with nginx? I presume with a combination of try_files and regex.

It's actually a static site that I'm trying to improve performance of, it only changes when I make changes to its content and has no dynamic elements, stale cache is not a problem.

0 likes
3 replies
goldtaste's avatar

I haven't done something like this myself in laravel, but guess you could write another middleware that checks if an html file exists for the route and returns a response with the content of your html page before the controllers are hit. You could possibly use some sort of file (or maybe even the cache) for mapping routes to html files. Then just update the mapper each time you create a new html file. Hope that sort of makes sense.

zoidq's avatar
Level 7

Thanks for your suggestion, appreciated.

My thinking is that by eliminating laravel and php-fpm all together and just serving static html with nginx directly I could significantly increase response times.

goldtaste's avatar

Ahh, yeah makes sense. Not too sure going through laravel will be too expensive if you are effectively just grabbing from a cache. Usually it's the db that really slows things down. But see your point. My nginx is a bit rusty, so not too sure if you can add some sort of re-write rules to your site config that can do the mapping for you. I suspect it may be quite difficult as you may need to do some logical checks like : if html file does not exist use index.php. Don't know if you can get that complicated with nginx. Maybe someone else on here knows a bit more about nginx. Let me know if you find a solution, as would be interested to see how it works.

Please or to participate in this conversation.