Php fpm webp nginx

How to Configure WebP Express to Serve WebP Images on Nginx

Third-Party Software Notice Our support team cannot provide support for third-party software and services. However, if you need assistance or spot an issue with this article please post in the GridPane Community Forum, and we will make necessary updates/improvements where needed.

One of our awesome clients brought the WebP Express plugin to my attention recently, and if you’re looking for an alternative to Shortpixel that simply takes care of the .jpeg/.png conversion to .webp and serves them, this plugin is well worth checking out.

Step 1. Install and Configure the Plugin

Install the plugin on your chosen site, then head to Dashboard > Settings > WebP Express to open the configuration page.

Ignore all the messages about .htaccess. This is only for Apache / LiteSpeed / OpenLiteSpeed. We’ll be setting our rules for Nginx directly on our server in the next steps. The plugin author has streamlining the UI for Nginx on their roadmap for the future.

The plugin offers multiple settings for image quality and different conversion methods. Fine tune them as you see fit. In my testing I left the defaults, and the “cwebp” conversion method worked perfectly well.

Step 2. SSH into your server

Please see the following articles to get started:

Step 3: Create webp-mappings.conf

We first need to create an Nginx configuration (aka config / .conf) file so that our server can serve WebP files. This first config makes use of the HTTP Context which applies server-wide.

Читайте также:  Java get implementation class

HTTP Context includes the following:

http include /etc/nginx/common/basics.conf; 
#include /etc/nginx/common/geoip.conf;
include /etc/nginx/common/limits.conf;
include /etc/nginx/mime.types;
include /etc/nginx/common/ssl.conf;
include /etc/nginx/common/logging.conf;
include /etc/nginx/common/6g-mappings.conf;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/extra.d/http-context.conf;
include /etc/nginx/sites-enabled/*;
>

We’ll make use of the include highlighted in red to create our new config, which ensures that any .conf file added to the /etc/nginx/conf.d/ directory applies server-wide.

This step will only need to be set up once per server. If you’re using WebP Express on more than one site, you can skip this step for your 2nd site onwards.

So, to summarise, we’ll create a file called webp-mappings.conf in the /etc/nginx/conf.d/ directory.

CREATE WEBP-MAPPINGS.CONF

Create the file with the following command:

nano /etc/nginx/conf.d/webp-mappings.conf

Paste the following block of code:

map $http_accept $webp_suffix default ""; 
"~*webp" ".webp";
>

Now Ctrl+O and then press Enter to save the file. Then Ctrl+X to exit nano.

Step 4: Create webp-main-context.conf

Create a site-specific configuration

We need to create a file called webp-express-main-context.conf in /var/www/site.url/nginx .

Create the file with the following, switching out “site.url” with your website’s domain:

nano /var/www/site.url/nginx/webp-express-main-context.conf

Paste the following block of code:

# WebP Express rules # -------------------- location ~* ^/?wp-content/.*\.(png|jpe?g)$ < add_header Vary Accept; expires 365d; if ($http_accept !~* "webp")< break; >try_files /wp-content/webp-express/webp-images/doc-root/$uri.webp $uri.webp /wp-content/plugins/webp-express/wod/webp-on-demand.php?xsource=x$request_filename&wp-content=wp-content ; > # Route requests for non-existing webps to the converter location ~* ^/?wp-content/.*\.(png|jpe?g)\.webp$ < try_files $uri /wp-content/plugins/webp-express/wod/webp-realizer.php?wp-content=wp-content ; >

Now Ctrl+O and then press Enter to save the file. Then Ctrl+X to exit nano. You can now proceed to step 5.

Step 5: Check and reload Nginx

Finally, we need to check if the conf files are correct then reload Nginx.

Читайте также:  Require once syntax php

Test your nginx syntax with:

If there are no errors present, reload nginx with the following command:

Источник

Как настроить WebP Express в WordPress на Nginx

wordpress-logo

Сегодня поговорим о том, как можно настроить WebP Express в WordPress на Nginx и PHP-FPM.

Плагин WebP Express дает возможность на CSS WordPress организовать поддержку изображение с расширением *.webp

Сам плагин легко устанавливается из консоли WordPress, а вот его настройка в связке с Nginx вызывает затруднение. Давайте пройдем все этапы по настройке WebP Express вместе с вами. И разберемся как можно настроить WebP Express в CMS WordPress с WEB-сервером Nginx.

Сам процесс установки в данной статье я описывать не буду. Думаю и сами разберетесь. Приступим сразу к его настройке.

Настройка WebP Express в WordPress на Nginx

WebP Express

  • Operation mode — устанавливаем в положение Varied image responses.
  • Scope — устанавливаем в Uploads and themes, данный параметр отвечает за преобразование файлов в данных папках.
  • Images types to work on — устанавливаем в Both jpeg and pngs, данный параметр отвечает за то, какие расширения файлов преобразовывать в WebP.
  • Destination folder — тут выбираем в какой папке хранить уже преобразованные файлы. Есть два варианта: оставить в той же или помещать в другую.
  • Destination structure — если вы выбрали перемещать преобразованные файлы в другую папку, то в данном пунке уже выбираем название папки: image-roots или document-root.
  • Cache control header — можно установить кэш для изображений.

Переходим к следующей категории:

WebP Express

Данная категория помещает необходимые правила в файл .htaccess . Данные правила необходимы только если у Вас установлен Apache. Но на всякий случай я их оставил.

WebP Express

Здесь настраиваются правила для конвертации изображений в формат WebP. Оставляем без изменений. И так все норм.

WebP Express

Здесь указываются методы конвертирования для вашей системы.

Читайте также:  Compile python file to pycharm

Если у вас отключен метод cwebp, а при прохождении теста выдает: No cwebp binaries could be executed (permission denied for user: «www-data») . Значит у вас нехватает утилиты cwebp. Для установки в Ubuntu/Debian в терминале набираем следующее:

WebP Express

Тут плагин предлагает с конвертировать все имеющиеся изображения в формат *.webp . А также конвертировать изображения при их загрузке на сайт.

WebP Express

Категория AlterHTML отвечает за автоматическую вставку кода в ваши изображения. Без данного параметра отображение формата *.webp на сайте с WordPress и Nginx работать не будет.

После включения нам так же необходимо вставить код представленный ниже в файл .htaccess в корневой директории сайта:

 # Redirect to existing converted image in cache-dir (if browser supports webp) RewriteCond % image/webp RewriteCond % -f RewriteCond %/wp-content/webp-express/webp-images/doc-root/wp-content/uploads/$1.$2 .webp -f RewriteRule ^/?(.+)\.(jpe?g|png)$ /wp-content/webp-express/webp-images/doc-root/wp-content/uploads /$1.$2.webp [NC,T=image/webp,E=EXISTING:1,L] # Redirect images to webp-on-demand.php (if browser supports webp) RewriteCond % image/webp RewriteCond % -f RewriteRule ^/?(.+)\.(jpe?g|png)$ /wp-content/plugins/webp-express/wod/webp-on-demand.php?xsource- rel=xwp-content/uploads/$1.$2&wp-content=wp-content [NC,L]

После данной манипуляции у вас на сайте заработает конвертация и подстановка изображений формата *.webp .

Если есть вопросы, то пишем в комментариях.

Также можете вступить в Телеграм канал, ВКонтакте или подписаться на Twitter. Ссылки в шапке страницы.
Заранее всем спасибо.

RSS

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Сегодня я решил на свой сайт установить Яндекс Поиск для сайта. Здесь, может возникнуть вопрос — а чем меня не Читать

Ваши сайты на WordPress пытаются ломать? Мой VDS находится под мониторингом Zabbix’а. Вчера я стал активно получать на почту сообщения Читать

wordpress-logo

Иногда, после очередного обновления WordPress или при обновлении плагина вместо сайта и административной панели в браузере отображается запись «Сайт ненадолго Читать

wordpress-logo

Составил и отсортировал повторяющиеся пинг сервисы для блогов WordPress в 2019 году. Копируйте и пользуйтесь моим списком пинг сервисов чтобы Читать

Источник

Оцените статью