Applicable to:
- Plesk for Linux
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:CONFIG_TEXT: 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:
CONFIG_TEXT: 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.
Comments
1 comment
Hi Leonid Gukhman,
May I ask:
Would this return 404 error if the webp file is missing?
And if so, could you please edit it, to return asked jpg/png file, if they exist, but a webp version of them, does not?
Please sign in to leave a comment.