Joseph Edmonds

Simple Nginx Trick to Reduce Server Load

by Joseph Edmonds

by Joseph Edmonds

This is the kind of tiny optimsation that, along with many other sensible choices and optimisations, can add up to significantly better performance and lower hosting costs.

It is quite common to have some Nginx config along the lines of

location / {
    try_files $uri $uri/ /index.php$is_args$args;
}

What this does is tries the exact URL, tries the URL as a folder and if not, passes the request to PHP to be processed by website system, eg Magento/Symfony etc.

What that can mean is that 404 requests for static assests are causing PHP to fire up and process the request and return a 404. If that happens a lot, for whatever reason, it can represent a significant server load.

Instead you can do this

# make image/asset 404s get an nginx 404 rather than be handled by PHP
location ~* .(png|jpeg|ico|gif|css|js|webp|avif) {
    try_files $uri =404;
}

# now handle everything else with a PHP fallback
location / {
    try_files $uri $uri/ /index.php$is_args$args;
}

What this will do is for any request with an extension in the list png|jpeg|ico|gif|css|js|webp|avif then nginx will either server the file, or will return a normal Nginx 404. This will happen very quickly and PHP will not be bothered with the request at all.

Then any requests which are not for static assets will be handled with the normal block.

This is the kind of tiny optimsation that, along with many other sensible choices and optimisations, can add up to significantly better performance and lower hosting costs.

Facebook
Twitter
LinkedIn
About Joseph Edmonds

About Joseph Edmonds

Personal musings, tech tips, trivia and other things that might be interesting.

Get in touch today

Send me a message concerning your idea, problem, or question – and I’ll personally respond as soon as possible.

Connect with me on LinkedIn.