Here is the working code for using webp. Server section:
server { listen 80; server_name site.ru; rewrite ^(.*) https://site.ru$1 permanent; } server { listen 443 ssl http2; ssl_certificate /etc/nginx/ssl/site.pem; ssl_certificate_key /etc/nginx/ssl/site.key; server_name site.ru; root /var/www/site; index index.php; include snippets/webp.conf; include snippets/wp.conf; }
The webp processing is done in a snippet so that it can be easily disabled or added to another site (snippets / webp.conf):
if ($http_accept ~* "webp") { set $webp "A"; } if (-f $request_filename.webp) { set $webp "${webp}E"; } set $webfile $uri; if ( $webp = "AE" ) { set $webfile $uri.webp; } location ~* ^.+\.(jpg|jpeg|png|tiff)$ { expires max; add_header Vary Accept; add_header Cache-Control "public"; try_files $webfile $uri =404; }
Well, more or less a standard snippet for WordPress (snippets / wp.conf), you can use your own:
location ~ \.php$ { fastcgi_buffers 8 256k; fastcgi_buffer_size 128k; fastcgi_intercept_errors on; include fastcgi_params; try_files $uri = 404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass_header Set-Cookie; fastcgi_pass_header Cookie; fastcgi_ignore_headers Cache-Control Expires Set-Cookie; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass unix:/var/run/php-fpm.sock; fastcgi_index index.php; } location ~* ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|woff2|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf|htm|html)$ { expires max; add_header Cache-Control "public"; } location ~* ^.+\.(css|js)$ { expires 1y; add_header Cache-Control "max-age=31600000, public"; }
In webp.conf synpte, it is checked that the browser supports webp ( $http_accept
). Then it is checked whether there is a file of a type a картинка-с-расширением.webp
( $request_filename.webp
). If both conditions are met, then we give the browser a file with the extension .webp.
The code works for jpg, jpeg, pnp, tiff files, which must be duplicate files of the form
- picture.jpg.webp
- picture.png.webp
etc.
wordpress
label is superfluous here. - SeVlad