Applicable to:
- Plesk for Linux
Question
How to enable leverage browser caching (cache expiration) for nginx?
Answer
Leverage browser caching for nginx can be enabled by adding directives for webserver. Check out the following "Requirements and limitations" before proceed with enabling.
Requirements and limitations:
- Depending on the type of content that is served, it might be required to enable caching for Apache too since different types of content is served by either nginx or Apache: How to enable leverage browser caching for Apache in Plesk
- The main conditions for enabling nginx leverage browser caching are:
1. Disabled Serve static files directly by nginx and Proxy mode options in Domains > example.com > Apache & nginx Settings.
(When it is enabled, the location directive is added to nginx configuration and further specified location directives (like in Additional nginx directives) with regular expressions will be ignored. Refer to official nginx documentation for details)
2. Website's docroot does not protected with password in Domains > example.com > Password-Protected Directories. - If Google PageSpeed Insights extension is used on the server and leverage browser caching for nginx is enabled globally, then the functionality of Google PageSpeed Insights is being broken.
Warning: Any customization made is done at your own will and risk and it is bound to be possibly overwritten by a Plesk update/upgrade process
Leverage browser caching can be enabled for a domain or server-wide.
-
Go to Domains > example.com > Apache & nginx Settings.
-
Check the Enable nginx caching checkbox, disable the Serve static files directly by nginx checkbox and click OK/Apply.
-
Log in to the server via SSH as root.
-
Create an additional nginx configuration file:
# touch /etc/nginx/conf.d/expires.global
-
Open this file using text editor and paste following directives into it:
CONFIG_TEXT: location ~* \.(js|jpg|jpeg|gif|png|css|tgz|gz|rar|bz2|doc|pdf|ppt|tar|wav|bmp|rtf|swf|ico|flv|txt|woff|woff2|svg)$ {
etag on;
if_modified_since exact;
add_header Pragma "public";
add_header Cache-Control "max-age=31536000, public";
} -
Create a directory for custom configuration templates:
# mkdir -p /usr/local/psa/admin/conf/templates/custom/domain/
-
Copy default nginx template to the newly created directory:
# cp -p /usr/local/psa/admin/conf/templates/default/domain/nginxDomainVirtualHost.php /usr/local/psa/admin/conf/templates/custom/domain/
-
Open
/usr/local/psa/admin/conf/templates/custom/domain/nginxDomainVirtualHost.php
with text editor and add the following line in the bottom of the file:CONFIG_TEXT: include /etc/nginx/conf.d/expires.global;
So, the bottom of
/usr/local/psa/admin/conf/templates/custom/domain/nginxDomainVirtualHost.php
file should look like:CONFIG_TEXT: . . .
include /etc/nginx/conf.d/expires.global;
<?php if (is_file($VAR->domain->physicalHosting->customNginxConfigFile)): ?>
include "<?php echo $VAR->domain->physicalHosting->customNginxConfigFile ?>";
<?php endif ?>
}As a result, all newly created domains will have leverage browser caching automatically enabled.
-
In order to apply this to all existing domains, it is required to reconfigure all the domains with the following command:
# /usr/local/psa/admin/bin/httpdmng --reconfigure-all
Warning: Consider running the above command during the maintenance time as it may cause some downtime for websites.
Note: the aforementioned directives will set etag header. That means that the content will be stored on the client side and not be refreshed until it is modified on the server. Alternatively, the expiration time can be specified explicitly using the following directives:
CONFIG_TEXT: location ~* \.(js|jpg|jpeg|gif|png|css|tgz|gz|rar|bz2|doc|pdf|ppt|tar|wav|bmp|rtf|swf|ico|flv|txt|woff|woff2|svg)$ {
expires 30d;
add_header Pragma "public";
add_header Cache-Control "public";
}
Where expires
directive means how long cache will be stored. The value can be specified in days (expires 30d
), hours (expires 2h
) or minutes (expires 15m
).
Comments
49 comments
nginx not ngnix :P
@minzkung Thanks! I corrected it :)
Is possible to enable globally?
@Horacio Stolovitzky, Hi! Please check this article again, it now contains the steps how to enable it globally.
Hi, after implementing this(not globally), my dynamic website stopped showing styles, images, etc.., and loading has time increased from 1.5s to +-10s. What can cause that?
Leverage Browser Caching you should use the plugin: Leverage Browser Caching
link down: https://wordpress.org/plugins/leverage-browser-caching/
I used for website: http://www.thuocmaxman.vn/ and get 99/100 points. only ... / google analytics.js (2 hours)
@Bogdan Dovgopol
Instructions in the article cannot increase loading time. It looks like some rewrite directives are missing.
@Thanhkieu2022
Thank you for sharing this information. This is another way of enabling Leverage Browser Caching.
Other Pleskians may find it useful.
Tried on Wordpress. Wordpress is not compatible with this. Will result in 404.
@Sharul
For Wordpress try this plugin.
@Thanhkieu2022, @Ivan Postnikov
This plugin is only for Apache but this is article about leverage browser caching for nginx. Please don't post wrong information.
@Miomir
Thank you for the notice about the plugin.
I have double checked it. It is applicable for Apache only.
This works if you add under Apache & nginx Settings in Additional nginx directives:
Add Expires Headers
Add Cache-Control Headers
Thank you very much for all amazing and helpful articles.
I use nginx only in subscription settings (service plans)
Please, please, for all those who use this environment it would be the greatest gift if you could write also support articles for using
only nginx
Wish you all the best. PLESK is awesome...
Hello @Markus!
Thank you for the feedback.
Sure, new articles are driven by demand. If there will be questions or issues regarding using Nginx only, the corresponding articles will be created.
This works well for my WordPress installation and sets the expires headers that I'm after, however URLs for "virtual files" that don't physically exist on the server in WordPress [such as robots.txt] now return a 404 page. I believe this is because no further Nginx processing takes place after the headers are set with the location directive.
Much advice on the internet suggests the use of try_files directive but the solution I am looking for is more along the lines of "for any file that doesn't physically exist on the server, ask Apache for it". Is something along these lines possible?
I give robots.txt as an example but the solution needs to be generic so it can also handle secure files that are stored outside of the webroot with rewriting carried out by Apache.
***EDIT***
From digging into the NGINX docs I see that what I actually want is a nested location directive - the initial block is lifted from the default nginx config within plesk, the second block adds expires headers to relevant files:
location / {
proxy_pass http://77.68.75.xxx:7080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Accel-Internal /internal-nginx-static-location;
access_log off;
location ~* \.(js|jpg|jpeg|gif|png|css|tgz|gz|rar|bz2|doc|pdf|ppt|tar|wav|bmp|rtf|swf|ico|flv|woff|woff2|svg|ttf)$ {
etag on;
if_modified_since exact;
add_header Pragma "public";
add_header Cache-Control "max-age=1209600, public";
}
}
I can test the above by manually editing the /vhosts/system/[domain]/conf/nginx.conf file and restarting nginx systemctl restart nginx.
This directive can't be applied using the Additional Nginx Directives option within plesk as a location directive for / already exists in the template, so any changes will be overwritten each time nginx.conf is recreated. How/where can I amend the plesk nginx template so that the individual vhost conf files that are generated use this modified directive?
Hello, @Peter Shaw.
Please try combining the directives with the ones specified in the following knowledge base article:
A WordPress website on a Plesk server shows "404 Not Found" on all pages except index.php, when running on FPM by nginx
Any disadvantages to enable this for all Customers?
Does it make more CPU / RAM Load?
@Lenor
> Does it make more CPU / RAM Load?
No
> Any disadvantages to enable this for all Customers?
It might affect some customers websites. For example, if the content was changed but the web browser may keep using the old version from the local cache as the content is yet to be expired.
in your article about enabling gzip compression, you advise to create
/etc/nginx/conf.d/gzip.conf
(which will be automatically picked up because of wildard include in nginx.conf)
but in this article you advise creating
/etc/nginx/conf.d/expires.global
and then adding include rule inside
/usr/local/psa/admin/conf/templates/default/domain/nginxDomainVirtualHost.php
why the difference? what are the (dis-)advantages of one approach over the other?
@Tomasz Paluszkiewicz
Because "location" directive is not allowed in "http" context.
@Robert Asilbekov
but then, gzip compression could also be applied the same way as expiry rules, right?
@Tomasz Paluszkiewicz
Correct, gzip compression could be also enabled this way. But it is better to enable gzip globally in "http" context and later it can be turned off for a particular subscription.
Because gzip contexts are:
http
,server
,location
,if in location
@Peter Shaw
Hi! Please refer to our documentation here. You can edit nginx template, so the directive will be applied to all domains.
Thanks @Alisa Kasyanova,
Created /usr/local/psa/admin/conf/templates/custom/domain/service/proxy.php and copied in the corresponding file from /templates/default. Added the following block below 'access_log off;':
access_log off;
<?php /** add expires headers where required. **/ ?>
location ~* \.(js|jpg|jpeg|gif|png|css|tgz|gz|rar|bz2|doc|pdf|ppt|tar|wav|bmp|rtf|swf|ico|flv|woff|woff2|svg|ttf)$ {
etag on;
if_modified_since exact;
add_header Pragma "public";
add_header Cache-Control "max-age=86400, public";
}
Regenerate nginx configuration files with /usr/local/psa/admin/bin/httpdmng --reconfigure-all
EDIT ***
The above is along the right lines but it is not the correct solution to the issue as ther resulting nginx.conf file doesn't give the desired headers for all requests - some requests for virtual files are not passed on when they should be.
@Peter Shaw
I suppose it is because the resulting nginx configuration file for a domain (you can check any, say, /etc/nginx/plesk.conf.d/vhosts/example.com.conf) has a location directive inside another location directive.
Try to add lines starting from "location..." to /usr/local/psa/admin/conf/templates/custom/domain/nginxDomainVirtualHost.php . For example, before "<?php if (!$VAR->domain->physicalHosting->proxySettings['nginxTransparentMode'] " and reconfigure the files. Then check the /etc/nginx/plesk.conf.d/vhosts/example.com.conf) again: it should have the "location..." as a separate section.
Hope it helps!
I think this article should be listed in Additional Information here.
Additional nginx directives/Leverage browser caching are ignored for a WordPress website
https://support.plesk.com/hc/en-us/articles/360014674853
(via https://talk.plesk.com/threads/browser-caching-suddenly-disabled.350651)
@Cirrus Tecnologia
Thank you for the feedback!
Indeed, this link will be useful here. I've updated the article accordingly.
Leverage doesn't have browser caching
Help pls website: https://gokkusagikoltukyikama.com
NGINX
location ~* .(js|jpg|jpeg|gif|png|css|tgz|gz|rar|bz2|doc|pdf|ppt|tar|wav|bmp|rtf|swf|ico|flv|txt|woff|woff2|svg)$ {
expires max;
add_header Pragma "public";
add_header Cache-Control "public";
}
Hello @Taha AK,
As I can see from the provided screenshot the leverage browser caching does not work for Google Analytics only, as it does not host on your server.
If you would like to get rid of this warning, I recommend you to check the possibility of hosting Google analytics.js file locally.
For more information on this matter, please contact Google Analytics Support or search for possible solutions around the Internet.
Please sign in to leave a comment.