使用 Varnish 加速 Apache 和 Drupal

Varnish 是一种 Web 应用程序加速器,可为大多数 Web 应用程序提供轻松的速度提升,Drupal 也不例外。它的工作原理是创建一个位于 Web 服务器前面的反向代理服务并缓存通过它的流量。当页面被请求时,Varnish 将请求转发到 Web 服务器以完成请求,然后从 Web 服务器返回的响应被 Varnish 缓存。这意味着对同一页面的下一个请求是由 Varnish 提供的,而不是由 Web 服务器提供的,从而大大提高了速度。

将 Varnish 与 Drupal 等应用程序一起使用的结果是,当发出请求时,不会命中 Web 服务器(以及 PHP),也不会命中数据库。Varnish 最适合处理匿名流量的 Drupal,因为经过身份验证的流量需要 cookie 和自定义 HTML。即便如此,您仍然可以看到网站上任何匿名流量的速度大幅提高。

Varnish 可以配置为在一堆 Apache 节点前作为独立机器运行,或者作为单个 Apache 服务器的前端运行。

在 Apache 上使用 Drupal 启动和运行 Varnish 有几个步骤,从安装 Apache 开始。

安装和配置 Apache

要在 Ubuntu 上安装 Apache,请使用以下 apt-get 命令。

sudo apt-get install apache2 apache2-mpm-prefork apache2-utils

安装后,您需要更改 Apache 侦听的端口。这是因为 Varnish 将被配置为侦听端口 80 并充当您指定的内部端口的代理。这里通常的方法是使用端口 8080,因为这是正常的替代 HTTP 端口,因此不会与其他任何端口发生冲突。

要更改 Apache 侦听的端口,只需打开文件/etc/apache2/ports.conf并将“侦听”指令更改为 8080。

Listen 8080

阻止外部世界访问端口 8080 可能是一个好主意。尽管这不是一个大的安全漏洞,但允许您的用户绕过您的 Varnish 服务器是一种不好的做法。这可以通过 Apache 配置选项或通过防火墙规则来完成。

完成后,只需重新启动 Apache 即可获取更改。此命令将在大多数 Linux 机器上执行此操作。

sudo service apache2 restart

随着 Apache 的启动和运行,现在是安装和配置 Varnish 的时候了。

安装和配置清漆

要在 Ubuntu 上安装 Varnish,只需运行以下 apt-get 命令。

sudo apt-get install varnish

安装后,您将找到以下三个对运行 Varnish 很重要的文件。

  • /etc/default/varnish - 这是一个 shell 脚本片段,/etc/init.d/varnish 使用它来运行带有各种选项的 Varnish。

  • /etc/varnish/default.vcl - 这是一个用于控制 Varnish 如何处理不同请求的文件。这适用于 Varnish 如何处理 cookie 以及应从缓存中排除哪些路径。此文件的位置在 /etc/default/varnish 文件中设置。

  • /etc/varnish/secret - 这是一个文件,用于安全地允许对 Varnish 缓存的管理访问。同样,此文件的位置在 /etc/default/varnish 文件中设置。

/etc/varnish/default 文件只需要创建变量 DAEMON_OPTS、NFILES 和 MEMLOCK,这些变量由 /etc/init.d/varnish 脚本选取。/etc/varnish/default 文件本质上是使用varnishd命令在命令行上运行 Varnish 的包装器。

DAEOMON_OPTS 变量控制 Varnish 工作方式的各个方面,包括 Varnish 应该侦听的端口,因此是该文件中最重要的部分。添加到此变量的任何选项都会直接传递给 varnishd 服务。以下选项可以包含在 DAEMON_OPTS 变量中以控制 Varnish 的运行方式。

  • -a - Varnish 应该侦听传入流量的端口。

  • -T - 管理界面的位置和端口。

  • -f - Varnish 配置文件的位置,通常存储在 /etc/varnish/default.vcl。

  • -S - Varnish 机密文件的位置,通常存储在 /etc/varnish/secret。

  • -s - 设置 Varnish 缓存的位置和大小选项。

  • -w - 配置线程池的最小、最大和超时长度。

  • -p - 设置多个可调参数之一。这可以多次使用以设置多个参数。

有关可用命令行参数的更多信息,请参阅有关 varnishd 命令的官方文档。

以下是设置一些默认值的 /etc/default/varnish 文件的简单示例。这通常用作在资源有限的机器上进行 Varnish 的基本设置。

# Should we start varnishd at boot?  Set to "no" to disable.
START=yes
 
# Maximum number of open files (for ulimit -n)
NFILES=131072
 
# Maximum locked memory size (for ulimit -l)
# Used for locking the shared memory log in memory.  If you increase log size,
# you need to increase this number as well
MEMLOCK=82000
 
# Default varnish instance name is the local nodename.  Can be overridden with
# the -n switch, to have more instances on a single server.
INSTANCE=$(uname -n)
 
DAEMON_OPTS="-a :80 \
             -T localhost:6082 \
             -f /etc/varnish/default.vcl \
             -S /etc/varnish/secret \
             -s malloc,256m"

这会将 Varnish 设置为具有以下选项:

  • 第 2 行 - 将 START 变量设置为“yes”,以便在服务器重新启动时启动 Varnish。

  • 第 5 行 - 将 NFILES 变量设置为 131072。这控制了 Varnish 可以同时打开多少个文件。当 Varnish 启动时,命令ulimit -n ${NFILES:-131072}在init.d文件中运行。

  • 第 10 行 - 将 MEMLOCK 变量设置为 82000。这控制用户如何软限制可能锁定到内存中的最大大小。当 Varnish 启动时,命令ulimit -l ${MEMLOCK:-82000} 在init.d文件中运行。

  • 第 14 行 - 将 INSTANCE 变量设置为“uname -n”的输出。当 Varnish 被配置为节点集群的一部分时使用,在这种情况下我们不会使用它。

  • 第 16 行 - 将 DAEMON_OPTS 变量设置为具有以下选项:

    • 使用 -a 标志从任何地方将端口号设置为 80。

    • 使用 -T 标志将本地计算机上的管理端口设置为 6082。

    • 使用 -f 标志将 Varnish 配置文件设置为 /etc/varnish/default.vcl。

    • 使用 -S 标志将机密文件位置设置为 /etc/varnish/secret。

    • 设置 Varnish 将缓存存储在内存中,并使用 -s 标志将该内存设置为 256m。

以下是不同的 Varnish 设置,它调整了一些其他可用参数。此设置专为拥有更多资源的主机而设计。

# Should we start varnishd at boot?  Set to "no" to disable.
START=yes
 
# Maximum number of open files (for ulimit -n)
NFILES=131072
 
# Maximum locked memory size (for ulimit -l)
# Used for locking the shared memory log in memory.  If you increase log size,
# you need to increase this number as well
MEMLOCK=82000
 
# Default varnish instance name is the local nodename.  Can be overridden with
# the -n switch, to have more instances on a single server.
INSTANCE=$(uname -n)
 
# The minimum number of worker threads to start
VARNISH_MIN_THREADS=400
 
# The Maximum number of worker threads to start
VARNISH_MAX_THREADS=4000
 
# Idle timeout for worker threads
VARNISH_THREAD_TIMEOUT=120
 
DAEMON_OPTS="-a :80 \
             -T localhost:6082 \
             -w ${VARNISH_MIN_THREADS},${VARNISH_MAX_THREADS},${VARNISH_THREAD_TIMEOUT} \
             -p thread_pool_add_delay=2 \
             -p thread_pools=2 \
             -p session_linger=50 \
             -p sess_workspace=262144 \
             -f /etc/varnish/default.vcl \
             -S /etc/varnish/secret \
             -s malloc, 1024m"

正在逐行设置以下选项。

  • 第 2 行 - 将 START 变量设置为“yes”,以便在服务器重新启动时启动 Varnish。

  • 第 5 行 - 将 NFILES 变量设置为 131072。这控制了 Varnish 可以同时打开多少个文件。当 Varnish 启动时,命令ulimit -n ${NFILES:-131072}在init.d文件中运行。

  • 第 10 行 - 将 MEMLOCK 变量设置为 82000。这控制用户如何软限制可能锁定到内存中的最大大小。当 Varnish 启动时,命令ulimit -l ${MEMLOCK:-82000} 在init.d文件中运行。

  • 第 14 行 - 将 INSTANCE 变量设置为“uname -n”的输出。当 Varnish 被配置为节点集群的一部分时使用,在这种情况下我们不会使用它。

  • 第 17 行 - 设置一个名为 VARNISH_MIN_THREADS 的变量,用于存储 Varnish 将启动的最小工作线程数。

  • 第 20 行 - 设置一个名为 VARNISH_MAX_THREADS 的变量,用于存储 Varnish 将启动的最大工作线程数。

  • 第 23 行 - 设置一个名为 VARNISH_THREAD_TIMEOUT 的变量,用于存储工作线程的空闲超时。

  • 第 25 行 - 将 DAEMON_OPTS 变量设置为具有以下选项:

    • 使用 -a 标志从任何地方将端口号设置为 80。

    • 使用 -T 标志将本地计算机上的管理端口设置为 6082。

    • 使用 -w 标志配置 Varnish 将启动的最大和最小工作线程数。

    • 使用 -p 标志设置许多额外选项。这包括将线程池的数量设置为 2 并稍微减少会话被撤销之前应该经过的时间。

    • 使用 -f 标志将 Varnish 配置文件设置为 /etc/varnish/default.vcl。

    • 使用 -S 标志将机密文件位置设置为 /etc/varnish/secret。

    • 设置 Varnish 将缓存存储在内存中,并使用 -s 标志将该内存设置为 256m。

接下来,我们需要编辑default.vcl文件以告诉 Varnish 如何处理传入和传出的请求。该default.vcl文件使用一种称为 Varnish 配置语言的语言,Varnish 将其转换为在请求到达时执行的二进制代码。这可能是 Varnish 设置中最复杂的部分,尤其是在考虑 Drupal 时,因为我们需要执行诸如排除某些页面和检查 cookie 之类的操作。该文件包含许多设置组和子程序。您在此处定义的任何子例程都将覆盖 Varnish 为它们提供的默认实现。

我们在这个文件中配置的第一件事是后端集成。当我们在上一步设置 Apache 时,我们让 Apache 在端口 8080 上侦听传入请求,因此我们告诉 Varnish 在请求页面缓存时使用该端口。下面将在本地机器上配置和初始化一个默认的后端侦听器。

backend default {
  .host = "127.0.0.1";
  .port = "8080";
}

使用 Drupal 时应该注意的一件事是页面加载时间过长,尤其是在重建缓存或执行其他复杂操作时。出于这个原因,最好包含一些额外的参数来增加 Varnish 等待 Web 服务器响应的时间。如果没有这些超时参数,当 Drupal 响应时间过长时,您可能会看到随机出现的 Varnish 错误。这是修改后的默认后端侦听器。

backend default {
  .host = "127.0.0.1";
  .port = "8080";
  .connect_timeout = 2s;
  .first_byte_timeout = 30s;
  .between_bytes_timeout = 10s;
}

所述vcl_recv子例程包含在主本体的清漆配置逻辑的。这是在向 Varnish 发送请求时要触发的第一个子例程。这控制了 Varnish 如何处理 cookie 以及应该从缓存机制中包含或排除哪些 URL。这是一个相当长的子例程,但它有很好的文档记录,并且基本上定义了以下操作。

  • 发生后端故障时该怎么办。

  • 在代理标头中设置将用户的 IP 地址转发到服务器。

  • 存储缓存对象时要跳过的 URL。

  • 可选择阻止访问某些受限页面。

  • 为请求设置压缩处理。

  • 不要缓存可下载的文件,如 PDF 或 Word 文档。

  • 删除 Drupal 不需要知道的 cookie。

sub vcl_recv {
  # Use anonymous, cached pages if all backends are down.
  if (!req.backend.healthy) {
    unset req.http.Cookie;
  }
 
  # Allow the backend to serve up stale content if it is responding slowly.
  setreq.grace= 6h;
 
  # Pipe these paths directly to Apache for streaming.
  if (req.url ~ "^/admin/content/backup_migrate/export") {
    return (pipe);
  }
 
  # Set up the X-Forwarded-for header with the client IP address.
  if (req.restarts == 0) {
    if (req.http.x-forwarded-for) {
      set req.http.X-Forwarded-For = req.http.X-Forwarded-For + ", " + client.ip;
    }
    else {
      set req.http.X-Forwarded-For = client.ip;
    }
  }
 
  # Do not cache these paths.
  if (req.url ~ "^/status\.php$" ||
     req.url~ "^/update\.php" ||
     req.url~ "^/install\.php" ||
     req.url~ "^/batch/.*$" ||
     req.url~ "^/admin" ||
     req.url~ "^/admin/.*$" ||
     req.url~ "^/user" ||
     req.url~ "^/user/.*$" ||
     req.url~ "^/users/.*$" ||
     req.url~ "^/info/.*$" ||
     req.url~ "^/flag/.*$" ||
     req.url~ "^.*/ajax/.*$" ||
     req.url~ "^.*/ahah/.*$") {
       return (pass);
  }
 
  # Do not allow outside access tocron.phpor install.php.
  #if (req.url ~ "^/(cron|install)\.php$" && !client.ip ~ internal) {
    # Have Varnish throw the error directly.
  #  error 404 "Page not found.";
    # Use a custom error page that you've defined in Drupal at the path "404".
    # setreq.url= "/404";
  #}
 
   # Handle compression correctly. Different browsers send different
   # "Accept-Encoding" headers, even though they mostly all support the same
   # compression mechanisms. By consolidating these compression headers into
   # a consistent format, we can reduce the size of the cache and get more hits.=
   # @see: http:// varnish.projects.linpro.no/wiki/FAQ/Compression
   if (req.http.Accept-Encoding) {
     if (req.http.Accept-Encoding ~ "gzip") {
       # If the browser supports it, we'll use gzip.
       set req.http.Accept-Encoding = "gzip";
     }
     else if (req.http.Accept-Encoding ~ "deflate") {
       # Next, try deflate if it is supported.
       set req.http.Accept-Encoding = "deflate";
     }
     else {
       # Unknown algorithm. Remove it and send unencoded.
       unset req.http.Accept-Encoding;
     }
   }
 
  # Always cache the following file types for all users. This list of extensions
  # appears twice, once here and again in vcl_fetch so make sure you edit both
  # and keep them equal.
  if (req.url ~ "(?i)\.(pdf|asc|dat|txt|doc|xls|ppt|tgz|csv|png|gif|jpeg|jpg|ico|swf|css|js)(\?.*)?$") {
    unset req.http.Cookie;
  }
 
  # Remove all cookies that Drupal doesn't need to know about. We explicitly 
  # list the ones that Drupal does need, the SESS and NO_CACHE. If, after 
  # running this code we find that either of these two cookies remains, we 
  # will pass as the page cannot be cached.
  if (req.http.Cookie) {
    # 1. Append a semi-colon to the front of the cookie string.
    # 2. Remove all spaces that appear after semi-colons.
    # 3. Match the cookies we want to keep, adding the space we removed 
    #    previously back. (\1) is first matching group in the regsuball.
    # 4. Remove all other cookies, identifying them by the fact that they have
    #    no space after the preceding semi-colon.
    # 5. Remove all spaces and semi-colons from the beginning and end of the 
    #    cookie string. 
    set req.http.Cookie = ";" + req.http.Cookie;
    set req.http.Cookie = regsuball(req.http.Cookie, "; +", ";");    
    set req.http.Cookie = regsuball(req.http.Cookie, ";(SESS[a-z0-9]+|SSESS[a-z0-9]+|NO_CACHE)=", "; \1=");
    set req.http.Cookie = regsuball(req.http.Cookie, ";[^ ][^;]*", "");
    set req.http.Cookie = regsuball(req.http.Cookie, "^[; ]+|[; ]+$", "");
 
    if (req.http.Cookie == "") {
      # If there are no remaining cookies, remove the cookie header. If there
      # aren't any cookie headers, Varnish's default behavior will be to cache
      # the page.
      unset req.http.Cookie;
    }
    else {
      # If there is any cookies left (a session or NO_CACHE cookie), do not
      # cache the page. Pass it on to Apache directly.
      return (pass);
    }
  }
}

vcl_deliver子例程用于调整被漆被发布之前客户端的响应。此子例程最常见的用途是控制响应中将出现哪些 HTTP 标头。以下是 vcl_deliver 子例程的典型示例。

sub vcl_deliver {
  # Remove some security specific common headers.
  remove resp.http.Via;
  remove resp.http.X-Whatever;
  remove resp.http.X-Powered-By;
  remove resp.http.X-Generator;
  remove resp.http.X-Varnish;
  remove resp.http.X-Drupal-Cache;
  remove resp.http.Server;
 
  if (obj.hits > 0) {
    set resp.http.X-Varnish-Cache = "HIT";
  }
  else {
    set resp.http.X-Varnish-Cache = "MISS";
  }
}

第一部分删除了一些典型的 HTTP 标头,这些标头揭示了很多关于服务器和架构的信息。这通常被认为是一件坏事(主要是因为它使针对性攻击变得更加容易),因此应该将其删除。这些是像服务器这样的标头,它显示了正在使用的 Web 服务器(通常由 Apache 生成)和 X-Generator,它由 Drupal 生成。

该子例程的第二部分涉及设置“HIT”或“MISS”以显示 Varnish 是否返回缓存页面。这对于确保一切正常工作或诊断 Varnish 缓存控制的任何问题非常有用。

vcl_fetch子程序控制如何已成功从后台检索光油对待文件。该beresp变量可以在这里找到,可用于返回检索文档之前调整缓存设置。

子程序底部增加了对ban lurker的支持。这是一个 Varnish 进程,它贯穿缓存并禁止各种缓存对象。禁止是一种使缓存无效的快速方法,而无需从缓存本身中删除对象。下次从缓存中获取对象时,会对其进行评估以查看它是否已被禁止。如果有,则请求、存储和提供页面的新版本。

sub vcl_fetch {
  # We need this to cache 404s, 301s, 500s. Otherwise, depending on backend but 
  # definitely in Drupal's case these responses are not cacheable by default.
  if (beresp.status == 404 ||beresp.status== 301 ||beresp.status== 500) {
    setberesp.ttl= 10m;
  }
 
  # Don't allow static files to set cookies. 
  # (?i) denotes case insensitive in PCRE (perl compatible regular expressions).
  # This list of extensions appears twice, once here and again in vcl_recv so 
  # make sure you edit both and keep them equal.
  if (req.url ~ "(?i)\.(pdf|asc|dat|txt|doc|xls|ppt|tgz|csv|png|gif|jpeg|jpg|ico|swf|css|js)(\?.*)?$") {
    unset beresp.http.Set-Cookie;
  }
 
  # Allow items to be stale if needed.
  setberesp.grace= 6h;
 
  # Allow for Ban Lurker support.
  set beresp.http.x-url = req.url;
  set beresp.http.x-host = req.http.host;
}

在完全失败的情况下,调用vcl_error子例程。这用于向用户返回一个 HTML 错误页面,告诉他们他们试图访问的页面存在问题,然后将用户重定向到主页。如果没有这个,Varnish 将发布一个默认的“大师冥想”页面。

vcl_error 的第一部分是一个可选部分,可以取消注释以允许在后端服务器出现故障时重定向到另一个域。如果您想向用户显示一个漂亮的错误页面而不是 Varnish 发布的版本,则启用此功能很有用,但该站点需要单独配置。启用此功能还可防止站点在底层站点出现问题时不断重定向到自身。

sub vcl_error {
  # Redirect to some other URL in the case of a homepage failure.
  #if (req.url ~ "^/?$") {
  #  setobj.status= 302;
  #  set obj.http.Location = "http://backup.example.com/";
  #}
 
  # Otherwise redirect to the homepage, which will likely be in the cache.
  set obj.http.Content-Type = "text/html; charset=utf-8";
  synthetic {"
<html>
<head>
  <title>Page Unavailable</title>
  <style>
    body { background: #303030; text-align: center; color: white; }
    #page { border: 1px solid #CCC; width: 500px; margin: 100px auto 0; padding: 30px; background: #323232; }
    a, a:link, a:visited { color: #CCC; }
    .error { color: #222; }
  </style>
</head>
<body onload="setTimeout(function() {window.location= '/' }, 5000)">
  <div id="page">
    <h1>Page Unavailable</h1>
    <p>The page you requested is temporarily unavailable.</p>
    <p>We're redirecting you to the <a href="/">homepage</a> in 5 seconds.</p>
    <div>(Error "} +obj.status+ " " +obj.response+ {")</div>
  </div>
</body>
</html>
"};
  return (deliver);
}

的default.vcl,上述样品制作主要是由FourKitchens和Lullabot的完成产生一个Drupal特定的上光油的配置文件工作采取。这已经稍作调整,并且已经在一些生产环境中使用了几个月没有任何问题。

我没有在这里粘贴整个文件,而是创建了一个 Git 存储库并将default.vcl文件放在那里。随意下载它并在您自己的项目中使用。

有关 VCL 文件的更多信息,请查看 Varnish 站点上的 VCL 文档。

设置 Varnish 运行时时,您可以使用 -S 标志来规定机密文件的位置。在上面的示例中,我们将其设置为位置 /etc/varnish/secret。这是一个文件,用作安全地允许对 Varnish 缓存进行管理访问的一种方式。它不是设置 Varnish 的必需部分,但它有助于锁定系统,因此包含它是个好主意。当系统尝试访问 Varnish 管理界面时,它会被要求进行身份验证。身份验证发送秘密文件的内容,然后 Varnish 在允许连接之前将其与实际内容进行比较。

典型的 Varnish 机密文件的内容如下,但这是由 Varnish 在安装时生成的。

04788b22-e179-4579-aac7-f3541fb40391

当您添加了自己的 VCL 文件并设置了 Varnish 运行时,您需要重新启动该服务以获取这些更改。这是通过 service 命令完成的。

sudo service varnish restart

请注意,在某些 Linux 系统上,这可能是varnishd

当您访问您的网站时,您应该像正常的页面请求一样加载。要查看 Varnish 是否已成为请求过程的一部分,您需要查看从服务返回的标头。如果您看到 X-Varnish-Cache 标头,则说明 Varnish 正在运行。它将具有 HIT 或 MISS 的值。

顺便说一句,要检查从 Web 请求返回的标头,请使用带有 -I 标志的 curl 命令。

$ curl -I http://www.varnish.com/
HTTP/1.1 200 OK
Server: Apache/2.2.27 (Unix)
Etag: "1402232119-0"
Cache-Control: public, max-age=0
Last-Modified: Sun, 08 Jun 2014 12:55:19 +0000
Expires: Sun, 11 Mar 1984 12:00:00 GMT
Content-Type: text/html; charset=utf-8
Accept-Ranges: bytes
Date: Sun, 08 Jun 2014 13:09:33 GMT
Age: 0
Vary: Cookie,Accept-Encoding
X-Varnish-Cache: MISS

配置 Drupal

有了这一切,您仍然需要配置 Drupal 以与 Varnish 通信。如果您不这样做,那么 Varnish 将假定每个页面都将错过缓存,因此您的 Varnish 缓存根本不会真正作为缓存运行。

要让 Drupal 与 Varnish 通信,您需要安装 Varnish HTTP Accelerator 集成模块。启用模块后,您需要转到 /admin/config/development/varnish 的配置页面并设置 Varnish 选项。

    在 cron 上刷新页面缓存?- 我通常将其设置为“禁用”,以便 Varnish 负责缓存。启用此功能后,您会发现 cron 运行经常会清空整个 Drupal 缓存,而不是逐页完成。
  • Varnish 版本 - 本教程是关于安装和配置 Varnish 3。截至目前 Varnish 4 已经发布,但 Drupal 模块尚不支持此版本。

  • Varnish 控制终端 - 这是 Varnish 管理界面的位置。这是在我们编辑 /etc/default/varnish 文件并使用 -T 标志告诉 Varnish 在哪个端口上设置接口时设置的。由于 /etc/default/varnish 文件将其设置为 localhost:6082(这是默认值),您可以将 Drupal 中的值设置为相同。

  • Varnish Control Key - 这是包含在 Varnish 机密文件中的值。

  • Varnish 连接超时(毫秒)- 对于本地安装的 Varnish 服务器,将其设置为“100”就可以了。如果您有外部 Varnish 缓存,那么您可能希望将此值设置得稍高一些。

  • 清漆缓存清除 - 控制应启用哪种缓存清除。这里默认是使用 Drupal 的默认缓存机制,但是你也可以安装 Expire 模块来选择不同的缓存清除系统。将此设置为 None 将允许页面保留完整的 max-age 设置。

  • 清漆禁止类型 - 选择用于使缓存中的对象无效的清漆禁止类型。这可以设置为 Normal 或 Ban Lurker,我们在 Varnish VCL 文件中创建了支持。

  • 状态 - 如果一切都设置正确,那么您应该在页面底部看到一条通知,上面写着“正在运行清漆”。

  •  

  •  

  •  

启用和配置模块后,您仍然需要告诉 Drupal 将 Varnish 视为缓存后端。这是通过在settings.php文件中设置几个值来完成的。

// 添加 Varnish 作为页面缓存处理程序。
$conf['cache_backends'] = array('sites/all/modules/contrib/varnish/varnish.cache.inc');
//当我们在引导过程中调用钩子时,Drupal 7 不会缓存页面。这需要
// 被禁用。
$conf['page_cache_invoke_hooks'] = FALSE;

如果您使用的是 Expire 模块,那么您还需要包含以下配置选项。这为 Varnish 设置了一个新的缓存箱,可以在需要时清除它。

$conf['cache_class_external_varnish_page'] = 'VarnishCache';

如果您不使用 Expire 模块,则需要包含以下选项。这将使用 Varnish 替换默认页面缓存。

$conf['cache_class_cache_page'] = 'VarnishCache';

您可能会注意到您的页面仍未被缓存,这有两个原因。关于 Drupal 和 Varnish,首先要意识到的是,经过身份验证的流量会绕过 Varnish 缓存,因此如果您已登录,那么您将无法“命中”页面的缓存版本。如果匿名用户仍然看不到页面的缓存版本,那么您需要为匿名用户启用缓存。转到 Drupal 中的性能页面(位于 /admin/config/development/performance)并打开选项“为匿名用户缓存页面”。您现在应该开始看到正在发布的 Varnish 缓存页面。

通过查看返回的标题来仔细检查事情是否正常。如果 X-Varnish-Cache 标头显示“HIT”,则使用了 Varnish 缓存。在缓存预热后,您还应该看到速度的大幅提升。

您还可以通过查看网站 Is Varnish Working 来仔细检查您的 Varnish/Drupal 集成是否正常工作。这会查看您的设置是否生成了正确的标题,并会提示您要查找的内容,如果不是,则会进行更改。

Apache RPAF 模块

您可能会注意到的一件事是,尽管这里的所有内容都作为缓存系统运行,但您将无法看到访问者的 IP 地址。通过 $_SERVER['REMOTE_ADDR'] 变量在 PHP 中找到的所有 Apache 日志和任何 IP 地址都将显示为来自 127.0.0.1。这是因为请求来自 Varnish 服务器而不是最终用户。用户的 IP 地址被添加到 Varnish 发送的请求头中,并将在 X-Forwarded-For 头中。这是一个非标准标头,因此几乎所有内容都缺少用户的 IP 地址。

对此有很多解决方案,但我发现最稳定的是使用名为 Reverse Proxy Add Forward(也称为 RPAF)的 Apache 模块。要安装它,请使用以下 apt-get 命令。

sudo apt-get install libapache2-mod-rpaf

如果模块尚未启用,您可以使用以下命令启用它。

sudo a2enmod rpaf

剩下要做的就是编辑/etc/apache2/mods-enabled/rpaf.conf 中的RPAF 配置文件。该文件包含几个不同的选项,但基本上您只需要以下内容:

RPAFenable On
RPAFsethostname  On
RPAFproxy_ips    127.0.0.1 192.168. 10.0.0.
RPAFheader       X-Forwarded-For

这里设置的配置选项如下:

Option价值Notes
RPA启用Should this module be enabled? To turn off just set this value to 'Off'.
RPAFproxy_ips127.0.0.1 192.168。10.0.0。- What IP addresses to adjust requests for.
RPAF头文件X-Forwarded-For- 用于真实 IP 地址的标头。

此处还有一两个其他选项可用,但我发现并非所有平台都完全支持它们。不要试图通过让 Varnish 将用户的 IP 地址作为请求 IP 地址传递来解决此 IP 地址问题,因为您将无法将 Apache 端口侦听器锁定为仅本地流量。

有了这个配置文件,您需要重新启动 Apache 才能加载更改。您应该立即看到 Apache 访问日志和 Drupal 看门狗日志中的差异。

如果您使用 Centos,那么前面的大部分步骤将几乎相同。(除了一些默认的文件位置)。RPAF 的安装略有不同,需要从 github 获取预编译版本并使用 Yum 安装。以下命令将执行此操作。

sudo yum localinstall http://y-ken.github.com/package/centos/6/x86_64/mod_rpaf-fork-0.6-5.el6.x86_64.rpm

最后,Varnish 是加速 Drupal 站点的一种非常好的方式,但它并不是适用于所有情况的即插即用解决方案。您应该通读 VCL 文件并了解它所做的一切,以及这可能对您的站点产生的任何影响。重要的是要意识到,如果您运行仅登录站点或电子商务站点,那么 Varnish 可能仅适用于您的一小部分用户。允许 Varnish 处理经过身份验证的流量是可能的,但您需要查看称为 Edge Side Includes (EDI) 的东西,以便您可以在 Varnish 缓存层中打孔以显示自定义的用户内容。