Подводные камни при использовании кэширования в nginx. Настройка кэширования статики с помощью nginx в Debian fastcgi_hide_header: решаем проблемы с безопасностью

HTTP заголовок Expires наряду с несколькими другими заголовками, такими как Cache-Control позволяет управлять кэшем, тем самым сообщая, как долго запрашиваемый контент будет актуален. После того как «время жизни» истекает, кэш перестает быть актуальным, и возникает необходимость запрашивать исходный ресурс, чтобы узнать были ли изменения в контенте. Заголовок Expires является стандартным заголовком, регламентированным в протоколе HTTP, и поддерживается практически любым кэшом. Что касается заголовка Cache-Control, то он был введен в HTTP/1.1 , позволив тем самым предоставить возможность веб-мастерам осуществлять больший контроль над контентом, а так же решить ограничения связанные с Expires. Чтобы использовать Cache-control эффективно, рекомендуется указывать время, по истечении которого кэш перестает быть актуальным.

В данном посту мы рассмотрим примеры настройки параметра expires в Nginx. Для начала попробуем в настройках выставить максимальный возможный срок хранения кэша.
Ставим кэш на максимальный срок

Server { ... location ~* ^.+\.(jpg|gif|png)$ { expires max; } ... }

Часто используемое значение времени кэширования может быть указано в днях, предположим в настройках нам необходимо выставить 7 дней, выглядеть это будет следующим образом.
Ставим кэш на неделю

Server { ... location ~* ^.+\.(jpg|gif|png)$ { expires 7d; } ... }

Таким образом, браузер после первого запроса файлов будет запрашивать их повторно лишь через 7 дней. Всё это время они будут находиться в кэше браузера пользователя. Есть возможность так же отсчитывать время жизни кэша от момента последнего изменения файла.
Ставим кэш от момента последнего изменения файла

Server { ... location ~* ^.+\.(jpg|gif|png)$ { expires modified 3d; } ... }

Используя такой метод, в результате мы получаем время кэша, которое будет зависеть от времени последней модификации файла. С момента последней модификации, браузер будет запрашивать файл через 3 дня. Для некоторых задач такой способ кэширования может оказаться более удобным.
Можно так же отключить кэширование файлов браузером, для этого выставляем значение параметра в off.
Отключаем кэширование файлов в браузере

Server { ... location ~* ^.+\.(jpg|gif|png)$ { expires off; } ... }

Заданное таким образом значение полностью отключает действие Сache-control. Используя кэширование, клиентская часть избегает необходимости скачивать контент целиком, т.к. он уже имеет локальные копии файлов. Выставлять время кэширования нужно осмысленно, без лишнего фанатизма, очень долгий кэш может быть не всегда рационален, если данные у вас меняются довольно динамично.

We all know that the performance of applications and web sites is a critical factor in their success. The process of making your application or web site perform better, however, is not always clear. Code quality and infrastructure are of course critical, but in many cases you can make vast improvements to the end user experience of your application by focusing on some very basic application delivery techniques. One such example is by implementing and optimizing caching in your application stack. This blog post covers techniques that can help both novice and advanced users see better performance from utilizing the included in NGINX and NGINX Plus.

Overview

A content cache sits in between a client and an “origin server”, and saves copies of all the content it sees. If a client requests content that the cache has stored, it returns the content directly without contacting the origin server. This improves performance as the content cache is closer to the client, and more efficiently uses the application servers because they don’t have to do the work of generating pages from scratch each time.

There are potentially multiple caches between the web browser and the application server: the client’s browser cache, intermediary caches, content delivery networks (CDNs), and the load balancer or reverse proxy sitting in front of the application servers. Caching, even at the reverse proxy/load balancer level, can greatly improve performance.

As an example, last year I took on the task of performance tuning a website that was loading slowly. One of the first things I noticed was that it took over 1 second to generate the main home page. After some debugging, I discovered that because the page was marked as not cacheable, it was being dynamically generated in response to each request. The page itself was not changing very often and was not personalized, so this was not necessary. As an experiment, I marked the homepage to be cached for 5 seconds by the load balancer, and just doing that resulted in noticeable improvement. The time to first byte went down to a few milliseconds and the page loaded visibly faster.

NGINX is commonly deployed as a reverse proxy or load balancer in an application stack and has a full set of caching features. The next section discusses how to configure basic caching with NGINX.

How to Set Up and Configure Basic Caching

Only two directives are needed to enable basic caching: proxy_cache_path and proxy_cache . The proxy_cache_path directive sets the path and configuration of the cache, and the proxy_cache directive activates it.

proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off; server { # ... location / { proxy_cache my_cache; proxy_pass http://my_upstream; } }

The parameters to the proxy_cache_path directive define the following settings:

  • The local disk directory for the cache is called /path/to/cache/ .
  • levels sets up a two‑level directory hierarchy under /path/to/cache/ . Having a large number of files in a single directory can slow down file access, so we recommend a two‑level directory hierarchy for most deployments. If the levels parameter is not included, NGINX puts all files in the same directory.
  • keys_zone sets up a shared memory zone for storing the cache keys and metadata such as usage timers. Having a copy of the keys in memory enables NGINX to quickly determine if a request is a HIT or a MISS without having to go to disk, greatly speeding up the check. A 1‑MB zone can store data for about 8,000 keys, so the 10‑MB zone configured in the example can store data for about 80,000 keys.
  • max_size sets the upper limit of the size of the cache (to 10 gigabytes in this example). It is optional; not specifying a value allows the cache to grow to use all available disk space. When the cache size reaches the limit, a process called the cache manager removes the files that were least recently used to bring the cache size back under the limit.
  • inactive specifies how long an item can remain in the cache without being accessed. In this example, a file that has not been requested for 60 minutes is automatically deleted from the cache by the cache manager process, regardless of whether or not it has expired. The default value is 10 minutes (10m). Inactive content differs from expired content. NGINX does not automatically delete content that has expired as defined by a cache control header (Cache-Control:max-age=120 for example). Expired (stale) content is deleted only when it has not been accessed for the time specified by inactive . When expired content is accessed, NGINX refreshes it from the origin server and resets the inactive timer.
  • NGINX first writes files that are destined for the cache to a temporary storage area, and the use_temp_path=off directive instructs NGINX to write them to the same directories where they will be cached. We recommend that you set this parameter to off to avoid unnecessary copying of data between file systems. use_temp_path was introduced in NGINX version 1.7.10 and .

And finally, the proxy_cache directive activates caching of all content that matches the URL of the parent location block (in the example, / ). You can also include the proxy_cache directive in a server block; it applies to all location blocks for the server that don’t have their own proxy_cache directive.

Delivering Cached Content When the Origin is Down

location / { # ... proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504; }

With this sample configuration, if NGINX receives an error , timeout , or any of the specified 5xx errors from the origin server and it has a stale version of the requested file in its cache, it delivers the stale file instead of relaying the error to the client.

Fine‑Tuning the Cache and Improving Performance

NGINX has a wealth of optional settings for fine‑tuning the performance of the cache. Here is an example that activates a few of them:

Proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off; server { # ... location / { proxy_cache my_cache; proxy_cache_revalidate on; proxy_cache_min_uses 3; proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504; proxy_cache_background_update on; proxy_cache_lock on; proxy_pass http://my_upstream; } }

These directives configure the following behavior:

  • proxy_cache_revalidate instructs NGINX to use conditional GET requests when refreshing content from the origin servers. If a client requests an item that is cached but expired as defined by the cache control headers, NGINX includes the If-Modified-Since field in the header of the GET request it sends to the origin server. This saves on bandwidth, because the server sends the full item only if it has been modified since the time recorded in the Last-Modified header attached to the file when NGINX originally cached it.
  • proxy_cache_min_uses sets the number of times an item must be requested by clients before NGINX caches it. This is useful if the cache is constantly filling up, as it ensures that only the most frequently accessed items are added to the cache. By default proxy_cache_min_uses is set to 1.
  • The updating parameter to the proxy_cache_use_stale directive, combined with enabling the proxy_cache_background_update directive, instructs NGINX to deliver stale content when clients request an item that is expired or is in the process of being updated from the origin server. All updates will be done in the background. The stale file is returned for all requests until the updated file is fully downloaded.
  • With proxy_cache_lock enabled, if multiple clients request a file that is not current in the cache (a MISS), only the first of those requests is allowed through to the origin server. The remaining requests wait for that request to be satisfied and then pull the file from the cache. Without proxy_cache_lock enabled, all requests that result in cache misses go straight to the origin server.

Splitting the Cache Across Multiple Hard Drives

If you have multiple hard drives, NGINX can be used to split the cache across them. Here is an example that splits clients evenly across two hard drives based on the request URI:

Proxy_cache_path /path/to/hdd1 levels=1:2 keys_zone=my_cache_hdd1:10m max_size=10g inactive=60m use_temp_path=off; proxy_cache_path /path/to/hdd2 levels=1:2 keys_zone=my_cache_hdd2:10m max_size=10g inactive=60m use_temp_path=off; split_clients $request_uri $my_cache { 50% “my_cache_hdd1”; 50% “my_cache_hdd2”; } server { # ... location / { proxy_cache $my_cache; proxy_pass http://my_upstream; } }

The two proxy_cache_path directives define two caches (my_cache_hdd1 and my_cache_hdd2) on two different hard drives. The split_clients configuration block specifies that the results from half the requests (50%) are cached in my_cache_hdd1 and the other half in my_cache_hdd2 . The hash based on the $request_uri variable (the request URI) determines which cache is used for each request, the result being that requests for a given URI are always cached in the same cache.

Please note this approach is not a replacement for a RAID hard drive setup. If there is a hard drive failure this could lead to unpredictable behavior on the system, including users seeing 500 response codes for requests that were directed to the failed hard drive. A proper RAID hard drive setup can handle hard drive failures.

Frequently Asked Questions (FAQ)

This section answers some frequently asked questions about NGINX content caching.

Can the NGINX Cache Be Instrumented?

add_header X-Cache-Status $upstream_cache_status;

This example adds an X-Cache-Status HTTP header in responses to clients. The following are the possible values for $upstream_cache_status :

How Does NGINX Determine Whether or Not to Cache Something?

By default, NGINX respects the Cache-Control headers from origin servers. It does not cache responses with Cache-Control set to Private , No-Cache , or No-Store or with Set-Cookie in the response header. NGINX only caches GET and HEAD client requests. You can override these defaults as described in the answers below.

proxy_cache_methods GET HEAD POST;

This example enables caching of POST requests.

Can NGINX Cache Dynamic Content?

Yes, provided the Cache-Control header allows for it. Caching dynamic content for even a short period of time can reduce load on origin servers and databases, which improves time to first byte, as the page does not have to be regenerated for each request.

Can I Punch a Hole Through My Cache?

location / { proxy_cache_bypass $cookie_nocache $arg_nocache; # ... }

The directive defines request types for which NGINX requests content from the origin server immediately instead of trying to find it in the cache first. This is sometimes referred to as “punching a hole” through the cache. In this example, NGINX does it for requests with a nocache cookie or argument, for example http://www.example.com/?nocache=true . NGINX can still cache the resulting response for future requests that aren’t bypassed.

What Cache Key Does NGINX Use?

The default form of the keys that NGINX generates is similar to an MD5 hash of the following NGINX variables : $scheme$proxy_host$request_uri ; the actual algorithm used is slightly more complicated.

Proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off; server { # ... location / { proxy_cache my_cache; proxy_pass http://my_upstream; } }

For this sample configuration, the cache key for http://www.example.org/my_image.jpg is calculated as md5(“http://my_upstream:80/my_image.jpg”) .

To change the variables (or other terms) used as the basis for the key, use the proxy_cache_key directive (see also the following question).

Can I Use a Cookie as Part of My Cache Key?

Yes, the cache key can be configured to be any arbitrary value, for example:

proxy_cache_key $proxy_host$request_uri$cookie_jessionid;

This example incorporates the value of the JSESSIONID cookie into the cache key. Items with the same URI but different JSESSIONID values are cached separately as unique items.

Does NGINX Use the ETag Header?

How Does NGINX Handle the Pragma Header?

The Pragma:no-cache header is added by clients to bypass all intermediary caches and go straight to the origin server for the requested content. NGINX does not honor the Pragma header by default, but you can configure the feature with the following proxy_cache_bypass directive:

Location /images/ { proxy_cache my_cache; proxy_cache_bypass $http_pragma; # ... }

Does NGINX Support the stale-while-revalidate and stale-if-error Extensions to the Cache-Control Header?

Does NGINX Support the Vary Header?

Further Reading

There are many more ways you can customize and tune NGINX caching. To learn even more about caching with NGINX, please take a look at the following resources:

  • The ngx_http_proxy_module reference documentation contains all of the configuration options for content caching.
  • Two webinars are available on demand and step through much of the information presented in this blog post: and .
  • The NGINX Plus Admin Guide has more configuration examples and information on tuning the NGINX cache.
  • The product page contains an overview on how to configure cache purging with NGINX Plus and provides other examples of cache customization.
  • The ebook provides a thorough deep‑dive on NGINX content caching.

Кеширование (caching) — это технология или процесс создания копии данных на быстродоступных носителях информации (кеш, cash). Проще говоря и применяя к реалиям сайтостроения, это может быть создание статической html-копии страницы или её части, которая генерируется с помощью PHP-скриптов (или иных других, как-то Perl, ASP.net), смотря на каком языке написан CMS сайта) и сохраняется на диске, в оперативной памяти или даже частично в браузере (рассмотрим подробнее ниже). Когда произойдёт запрос страницы от клиента (браузера), вместо того, чтобы заново собирать её скриптами, браузер получит её готовую копию, что намного экономнее по затратам ресурсов хостинга, и быстрее, так как передать готовую страницу занимает меньше времени (порой значительно меньше), чем её создание заново.

Зачем использовать кеширование на сайте

  • Для снижения нагрузки на хостинг
  • Для быстрой отдачи содержимого сайта браузеру

Оба аргумента, думаю, в комментариях не нуждаются.

Недостатки и отрицательный эффект от кеширования сайта

Как ни странно, у кеширования сайта есть и свои минусы. В первую очередь это касается сайтов, содержание которых динамично изменяется при взаимодействии с ним. Зачастую, это сайты, которые выдают содержимое или его часть с помощью AJAX. В общем-то, кеширование AJAX тоже возможно и даже нужно, но это тема для отдельного разговора и не касается традиционно используемых технологий, о которых пойдёт речь далее.
Также, проблемы могут возникнуть у зарегистрированных пользователей, для которых постоянный кеш может стать проблемой при взаимодействии с элементами сайта. Тут, как правило, кеш отключается, либо используется объектное кеширование отдельных элементов сайта: виджетов, меню и тому подобных.

Как настроить кеширование у себя на сайте

Для начала, надо разобраться какие технологии традиционно используются для кеширования содержимого сайтов.
Все возможные способы можно разделить на 3 группы

Кеширование на стороне сервера

Кеширование с помощью NGINX

Кеширование с помощью htaccess (Apache)

Если у вас есть доступ только к.htaccess , и рабочий сервер только Apache, то вы можете использовать такие приёмы, как сжатие gzip и выставление заголовков Expires , чтобы использовать браузерный кеш.

Включаем сжатие gzip для соответствующих MIME-типов файлов

AddOutputFilterByType DEFLATE text/plain text/html AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE text/javascript application/javascript application/x-javascript AddOutputFilterByType DEFLATE text/xml application/xml application/xhtml+xml application/rss+xml AddOutputFilterByType DEFLATE application/json AddOutputFilterByType DEFLATE application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon

Включаем заголовки Expires для статичных файлов сроком на 1 год (365 дней)

ExpiresActive on ExpiresDefault "access plus 365 days"

Кеширование с помощью Memcached

Кеширование с помощью акселератора php

Если движок сайта написан на PHP, то при каждой загрузке любой страницы сайта происходит исполнение скриптов php: интерпретатор кода читает скрипты, написанные программистом, генерирует из них байткод, понятный машине, исполняет его и выдаёт результат. Акселератор PHP позволяет исключить постоянную генерацию байткода, кешируя скомпилированный код в памяти или на диске, тем самым увеличивая производительность и уменьшая время, затрачиваемое на исполнение PHP. Из поддерживаемых на сегодня акселераторов существует:

  • Windows Cache Extension for PHP
  • XCache
  • Zend OPcache

В PHP версии 5.5 и выше уже встроен акселератор Zend OPcache , поэтому чтобы включить акселератор, вам достаточно просто обновить версию PHP

Кеширование на стороне сайта

Как правило, тут подразумевается возможность CMS сайта создавать статические html-копии страниц. Такой возможностью обладают большинство популярных движков и фреймворков. Лично я работал со Smarty, WordPress, поэтому могу заверить, что они отлично справляются со своей работой. В оригинальном WordPress из коробки нет кеширующих возможностей, которые необходимы любому малость нагруженному проекту, зато есть множество популярных плагинов для кеширования:

  1. , который как раз и занимается генерацией статических страниц сайта;
  2. Hyper Cache, который по сути работает так же, как и предыдущий плагин;
  3. DB Cache. Суть работы — кеширование запросов к базе данных. Тоже очень полезная функция. Можно использовать в связке с двумя предыдущими плагинами;
  4. W3 Total Cache. Оставил его на десерт, это мой любимый плагин в WordPress. С ним сайт преображается, превращаясь из неповоротливого автобуса в гоночный болид. Его огромным преимуществом является огромный набор возможностей, как то несколько вариантов кеширования (статика, акселераторы, Memcached, запросы к базе данных, объектное и страничное кеширование), конкатенация и минификация кода (объединение и сжатие файлов CSS, Javascript, сжатие HTML за счёт удаления пробелов), использование CDN и многое другое.

Что тут скажешь — используйте правильные CMS, и качественное кеширование будет доступно практически из коробки.

Кеширование на стороне браузера (клиента), заголовки кеширования

Кеширование в браузере возможно потому, что любой уважающий себя браузер это позволяет и поощряет. Возможно это благодаря HTTP заголовкам , которые сервер отдаёт клиенту, а именно:

  • Expires;
  • Cache-Control: max-age;
  • Last-Modified;
  • ETag.

Благодаря им пользователи, которые неоднократно заходят на сайт, тратят крайне мало времени на загрузку страниц. Заголовки кеширования должны применяться ко всем кешируемым статическим ресурсам: файлы шаблона, картинок, файлы javascript и css, если есть, PDF, аудио и видео, и так далее.
Рекомендуется выставлять заголовки так, чтобы статика хранилась не менее недели и не более года, лучше всего год.

Expires

Заголовок Expires отвечает за то, как долго кеш является актуальным, и браузер может использовать кешированные ресурсы, не запрашивая у сервера их новую версию. Является сильным и крайне желательным к использованию, так как действует в обязательном порядке. В заголовке рекомендуется указывать срок от недели до года. Больше года лучше не указывать, это является нарушением правил RFC.

Например, чтобы настроить Expires в NGINX для всех статических файлов на год (365 дней), в конфигурационном файле NGINX должен присутствовать код

Location ~* ^.+\.(jpg|jpeg|gif|png|svg|js|css|mp3|ogg|mpe?g|avi|zip|gz|bz2?|rar|swf)$ { expires 365d; }

Cache-Control: max-age;

Cache-Control: max-age отвечает за то же самое.
Более предпочтительно использование Expires, нежели Cache-Control ввиду большей распространённости. Однако, если Expires и Cache-Control будут присутствовать в заголовках одновременно, то приоритет будет отдан Cache-Control.

В NGINX Cache-Control включается так же, как и Expires , директивой expires: 365d;

Last-Modified и ETag

Эти заголовки работают по принципу цифровых отпечатков. Это означает, что для каждого адреса URL в кеше будет устанавливаться свой уникальный id. Last-Modified создаёт его на основе даты последнего изменения. Заголовок ETag использует любой уникальный идентификатор ресурса (чаще всего это версия файла или хеш контента). Last-Modified – «слабый» заголовок, так как браузер применяет эвристические алгоритмы, чтобы определить, запрашивать ли элемент из кеша.

В NGINX для статичных файлов ETag и Last-Modified включены по умолчанию. Для динамических страниц их либо лучше не указывать, либо это должен делать скрипт, генерирующий страницу, либо, что лучше всего, использовать правильно настроенный кеш, тогда NGINX сам позаботится о заголовках. Например, для WordPress, вы можете воспользоваться .

Эти заголовки позволяют браузеру эффективно обновлять кешированные ресурсы, отправляя запросы GET каждый раз, когда пользователь явным образом перезагружает страницу. Условные запросы GET не возвращают полный ответ, если ресурс не изменился на сервере, и таким образом обеспечивают меньшую задержку, чем полные запросы, тем самым уменьшая нагрузку на хостинг и уменьшая время ответа.

Одновременное использование Expires и Cache-Control: max-age избыточно, так же, как избыточно одновременное использование Last-Modified и ETag. Используйте в связке Expires + ETag либо Expires + Last-Modified.

Включить GZIP сжатие для статичных файлов

Конечно, сжатие GZIP не относится к кешированию как таковому напрямую, однако, весьма экономит трафик и увеличивает скорость загрузки страниц.

Как включить GZIP для статики в server { .... gzip on; gzip_disable "msie6"; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript; } Как включить GZIP для статики в Чтобы включить сжатие gzip в.htaccess, нужно в начало файла вставить следующий код: AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript

Wordpress далеко не самая производительная платформа для ведения блогов, и крупные сайты, как правило, используют кэширование для ускроения его работы. Для wordpress, есть много популярных дополнений реализующих кэширование, но все они на мой взгляд довольно осложненные, и, как правило, требуют либо установки дополнительного программного обеспечения, такого как, например, Varnish или memcached, либо перекладывают кэширование на плечи PHP который тоже производительным не назовешь. В этом посте я расскажу как настроить кэширование wordpress средствами nginx , без установки дополнительного ПО.

В nginx есть FastCGI модуль который предоставляет директивы, позволяющие кэшировать ответ от fastcgi. Использование данного модуля избавляет нас от необходимости использовать сторонние средства кэширования. Модуль так же позволяет нам не кэшировать часть ресурсов опираясь на различные параметры запроса, такие как, например: тип (GET, POST), куки, адрес страницы и другие. Сам модуль умеет исключительно добавлять в кэш, но не умеет его очищать или удалять отдельные записи из него. Без очистки кэша при добавлении, редактировании и добавлении комментария к посту кэш не будет обновляться, и сделанные изменения будут видны только с большой задержкой, поэтому для очистки кэша мы будем использовать сторонний nginx модуль - nginx_cache_purge .

Настройка nginx

В большинстве современных дистрибутивов nginx уже собран с модулем ngx_cache_purge , но на всякий случай проверим, что он присутствует. В консоли выполним:

nginx -V 2>& 1 | grep -o nginx-cache-purge

Если после выполнения команды вы видите nginx-cache-purge , то значит можно продолжать. Если после выполнения команды ничего не появилось, то у вас вероятно какой-то из старый дистрибутивов ubuntu, в котором nginx собран без поддержки этого модуля. В данном случае необходимо переустановить nginx из стороннего ppa:

sudo add-apt-repository ppa:rtcamp/nginx sudo apt-get update sudo apt-get remove nginx* sudo apt-get install nginx-custom

Настроим nginx. Откроем файл с настройками виртуального хоста, и приведем его к примерно такому содержимому:

fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m ; fastcgi_cache_key " $scheme$request_method$host$request_uri" ; fastcgi_cache_use_stale error timeout invalid_header http_500 ; fastcgi_ignore_headers Cache-Control Expires Set-Cookie ; # Upstream to abstract backend connection(s) for php upstream php { server unix:/var/run/php5-fpm.sock fail_timeout=0 ; } server { listen 80 ; server_name .example.com ; root /var/www/example.com/html ; index index.php ; error_log /var/www/example.com/log/error.log ; access_log /var/www/example.com/log/access.log ; set $skip_cache 0 ; # POST requests and urls with a query string should always go to PHP if ($request_method = POST) { set $skip_cache 1 ; } if ($query_string != "") { set $skip_cache 1 ; } # Don"t cache uris containing the following segments if ($request_uri ~ * "/wp-admin/|/xmlrpc.php|wp-.*.php|/feed/|index.php|sitemap(_index)?.xml") { set $skip_cache 1 ; } # Don"t use the cache for logged in users or recent commenters if ($http_cookie ~ * "comment_author|wordpress_+|wp-postpass|wordpress_no_cache|wordpress_logged_in") { set $skip_cache 1 ; } location / { try_files $uri $uri/ /index.php? $args ; } location ~ \.php$ { try_files $uri = 404 ; include fastcgi_params ; fastcgi_pass php ; fastcgi_cache_bypass $skip_cache ; fastcgi_no_cache $skip_cache ; fastcgi_cache WORDPRESS ; fastcgi_cache_valid 60m ; } location ~ /purge(/.*) { allow 127 .0.0.1 ; deny all ; fastcgi_cache_purge WORDPRESS " $scheme$request_method$host$1" ; } location ~ * ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf) $ { access_log off ; log_not_found off ; expires max ; } location ~ /\. { deny all ; access_log off ; log_not_found off ; } location = /favicon.ico { log_not_found off ; access_log off ; } location = /robots.txt { allow all ; log_not_found off ; access_log off ; } # Deny access to uploads that aren’t images, videos, music, etc. location ~ * ^/wp-content/uploads/.*.(html|htm|shtml|php|js|swf) $ { deny all ; } # Deny public access to wp-config.php location ~ * wp-config.php { deny all ; } }

Разумеется, параметры root , server_name , access_log , error_log необходимо исправить согласно тому, как у вас все настроенно. В строке fastcgi_cache_path /var/run/nginx-cache levels=1:2 keys_zone=WORDPRESS:100m inactive=60m; мы говорим nginx, что хранить кэш нужно в директории /var/run/nginx-cache/ , зону памяти называем WORDPRESS , максимальный размер кэша устанавливаем в 100 мегабайт и таймер сброса из-за неактивности устанавливаем в 60 минут. Приятным бонусом подобной конфигурации является то, что если по каким-то причинам наш PHP бекэнд перестает работать, nginx продолжит отдавать закэшированные страницы.

Настройка Wordpress

Сам nginx не знает, когда нужно очищать кэш, поэтому необходимо установить дополнение для wordpress, которое будет автоматически очищать кэш после изменений. Ставим дополнение nginx -t nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful

И если все хорошо - перезагружаем его:

systemctl reload nginx

Заходим на любую страницу, и проверяем что nginx добавил её в кэш:

ls -la /var/run/nginx-cache

Дополнительно: помещаем кэш nginx в ramdisk (tmpfs)

Сейчас у нас кэширование настроено, но кэш хранится на жестком диске, что не является хорошим решение. Оптимальнее будет смонтировать директорию с кэшем nginx в память. Для этого откроем /etc/fstab , и добавим туда:

tmpfs /var/run/nginx-cache tmpfs nodev,nosuid,size= 110M 0 0

Если в настройках nginx вы указали больший размер кэша, то параметр size необходимо изменить в соответствии с указанным размером кэша, плюс небольшой запас.
Сразу смонтируем директорию в память:

Теперь при каждой загрузке системы, директория /var/run/nginx-cache будет помещаться в память, что должно уменьшить время отдачи страницы.

Заключение

Не стоит рассчитывать на данный способ как на панацею. Интерпретатор PHP как я уже выше писал, нельзя назвать быстрым, да и сам Wordpress довольно большой и "тяжелый". Если страницы нет в кэше, или она редко запрашивается, то nginx всё равно сначала будет обращаться к не самому производительному бекэнду. Однако в целом, кэширование даст возможность вашему серверу немного расслабиться на генерации популярных постов, и в моменты публикации нового поста.

Это далеко не единственный способ ускорить ваш wordpress блог. Существует ещё масса других техник, о которых я напишу позже.