[How to] Enable cache expiration in nginx

Created:

2016-11-16 12:49:38 UTC

Modified:

2017-05-22 11:40:43 UTC

9

Was this article helpful?


Have more questions?

Submit a request

[How to] Enable cache expiration in nginx

Applicable to:

  • Plesk 12.5 for Linux
  • Plesk 11.5 for Linux
  • Plesk 12.5 for Windows

Question

How to enable cache expiration in nginx?

Answer

The following directive enables cache expiration in 1 minute:

    location ~* \\.(css|js|gif|jpeg|png)$ {
expires 1m;
add_header Cache-Control "public, must-revalidate, proxy-revalidate";
try_files $uri @fallback;
}

To change cache expiration to 1 hour or 1 day instead, use:

    1h;
1d;

Also it is needed to exclude files format from location (in this example css|js|gif|jpeg|png ) in Serve static files directly by nginx , if it is enabled.

It is not possible to enable cache expiration server-wide. Instead, Plesk allows custom settings at a service plan and website (virtual host) levels.

Website:

Add above directive in Subscriptions > example.com > Apache & nginx Settings > Additional nginx directives

Settings defined in Subscriptions > example.com > Apache & nginx Settings > Additional nginx directives are written in /var/www/vhosts/system/example.com/conf/vhost_nginx.conf file.

Service Plan:

Add above directive in Service Plans > plan_name > Web Server > nginx directives

Service plan level settings will be valid for all subscriptions under the plan.

Have more questions? Submit a request

2 Comments

  • 0
    Avatar
    Raymond Hawkins

    Note that this will not work if "Serve static files directly by nginx" is checked because it comes first and overwrites this rule.

    Edited by Raymond Hawkins
  • 1
    Avatar
    Vitaly Zhidkov

    @Raymond, this is expected and files format specified in location should be excluded from list of static files served by nginx.

Please sign in to leave a comment.