How to enable caching for static assets in nginx?

Published on Aug. 22, 2023, 12:19 p.m.

To enable caching for static assets in Nginx, you can follow these steps:

  1. Open the Nginx configuration file for your website. This file is usually located at /etc/nginx/sites-available/example.com or similar, depending on your server setup.
  2. Inside the server block, add the following directives:
location /static/ {
expires 7d;
}

This will cache any files under the /static directory for 7 days.
3. Reload the Nginx configuration for the changes to take effect:

sudo service nginx reload

Alternatively, you can also enable Nginx caching through the Plesk control panel. Here are the steps:

  1. Log in to the Plesk control panel and navigate to the domain’s settings.
  2. Go to Apache & Nginx Settings.
  3. Check the Enable nginx caching checkbox.
  4. Disable the Serve static files directly by nginx checkbox, as serving static files directly by Nginx can prevent caching from working correctly.
  5. Click OK to save the changes.

Enabling caching for static assets in Nginx can significantly improve the performance of your website and reduce the load on your server.

Tags: