Question
How to configure nginx to serve .webp images instead of jpg/png images when the website is running on nginx only?
Answer
In this example, we have a WebP copy of a jpg/png image with .webp extension next to the original file, for example:
- example.jpg
- example.jpg.webp
-
Connect to the Plesk server via SSH.
-
Create the file
/etc/nginx/conf.d/webp.conf
:# touch /etc/nginx/conf.d/webp.conf
-
Open the
webp.conf
file in a text editor (for example, vi editor) and paste the following content in it:map $http_accept $webp_extension { default ""; "~*webp" ".webp"; }
-
Save the changes and close the file.
-
Restart the nginx service to apply the changes:
# service nginx restart
-
Log in to Plesk and go to Domains > example.com > Apache & nginx settings.
-
Add the following to the additional nginx directives field:
location ~* ^.+.(jpe?g|png) {
add_header Cache-Control "public, no-transform";
add_header Vary "Accept-Encoding";
if ( !-f $document_root$uri$webp_extension ) {
add_header X_WebP_SP_Miss $document_root$uri$webp_extension;
}
try_files $uri$webp_extension $uri =404;
} - Make sure Serve static files directly by nginx checkbox is disabled.
-
Apply the changes.