Назад | Перейти на главную страницу

nginx: как я могу установить директивы proxy_ * только для соответствия URI?

Я занимаюсь этим часами и не могу найти чистого решения.

В принципе, у меня есть настройка прокси-сервера nginx, которая работает очень хорошо, но я хотел бы обрабатывать несколько URL-адресов вручную. В частности, есть 2-3 места, для которых я хотел бы установить proxy_ignore_headers в Set-Cookie, чтобы заставить nginx кэшировать их (nginx не кэширует ответы с Set-Cookie согласно http://wiki.nginx.org/HttpProxyModule#proxy_ignore_headers).

Поэтому для этих мест все, что я хотел бы сделать, это установить proxy_ignore_headers Set-Cookie;

Я перепробовал все, что мог придумать, кроме настройки и дублирования каждого значения конфигурации, но ничего не работает.

Я попытался:

Это должно быть так просто - изменение / добавление одной директивы для некоторых запросов, и все же я не смог заставить nginx сделать это.

Что мне здесь не хватает?

Есть ли хотя бы способ обернуть общие директивы в многократно используемый блок и указать на него несколько блоков местоположения после добавления своих уникальных битов?

Спасибо.

Для справки ниже приведено основное местоположение / блок вместе с моей неудавшейся директивой proxy_ignore_headers для определенного URI.

location / {
  # Setup var defaults
  set $no_cache "";

  # If non GET/HEAD, don't cache & mark user as uncacheable for 1 second via cookie
  if ($request_method !~ ^(GET|HEAD)$) {
    set $no_cache "1";
  }

  if ($http_user_agent ~* '(iphone|ipod|ipad|aspen|incognito|webmate|android|dream|cupcake|froyo|blackberry|webos|s8000|bada)') {
    set $mobile_request '1';
    set $no_cache "1";
  }

  # feed crawlers, don't want these to get stuck with a cached version, especially if it caches a 302 back to themselves (infinite loop)
  if ($http_user_agent ~* '(FeedBurner|FeedValidator|MediafedMetrics)') {
    set $no_cache "1";
  }

  # Drop no cache cookie if need be
  # (for some reason, add_header fails if included in prior if-block)
  if ($no_cache = "1") {
    add_header Set-Cookie "_mcnc=1; Max-Age=17; Path=/";
    add_header X-Microcachable "0";
  }

  # Bypass cache if no-cache cookie is set, these are absolutely critical for Wordpress installations that don't use JS comments
  if ($http_cookie ~* "(_mcnc|comment_author_|wordpress_(?!test_cookie)|wp-postpass_)") {
    set $no_cache "1";
  }

  if ($request_uri ~* wpsf-(img|js)\.php) {
    proxy_ignore_headers Set-Cookie;
  }

  # Bypass cache if flag is set
  proxy_no_cache $no_cache;
  proxy_cache_bypass $no_cache;

  # under no circumstances should there ever be a retry of a POST request, or any other request for that matter
  proxy_next_upstream off;
  proxy_read_timeout 86400s;

  # Point nginx to the real app/web server
  proxy_pass http://localhost;

  # Set cache zone
  proxy_cache microcache;

  # Set cache key to include identifying components
  proxy_cache_key $scheme$host$request_method$request_uri$mobile_request;

  # Only cache valid HTTP 200 responses for this long
  proxy_cache_valid 200 15s;

  #proxy_cache_min_uses 3;

  # Serve from cache if currently refreshing
  proxy_cache_use_stale updating timeout;

  # Send appropriate headers through
  proxy_set_header Host $host;
  # no need for this proxy_set_header X-Real-IP $remote_addr;
  # no need for this proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

  # Set files larger than 1M to stream rather than cache
  proxy_max_temp_file_size 1M;

  access_log /var/log/nginx/androidpolice-microcache.log custom;
}

Попробовав буквально 10 разных вещей и посоветовавшись с Фенн Бейли из http://fennb.com, Мне приходится прибегать к решению include, которое, кажется, единственное, что позволяет избежать дублирования кода и действительно работает.

Я переместил все директивы из местоположения / {} в их собственный файл и сделал следующее:

location / {
  include /etc/nginx/vhosts/androidpolice-root.conf;
}

location ~* wpsf-(img|js)\.php {
  include /etc/nginx/vhosts/androidpolice-root.conf;
  proxy_ignore_headers "Set-Cookie" "Cache-Control";
}

На данный момент я весьма шокирован негибкостью nginx, когда дело касается if и условных выражений - эти вещи должны быть такими тривиальными, но это не так.

Кстати, у меня последняя версия nginx 1.1.17.