如何使用 Varnish 设置 Nginx

arb*_*les 4 nginx varnish ruby apache-2.2 ruby-rack

我想看看如何配置 Nginx 和 Varnish。

我正在运行多个 PHP 站点和 Rack-Sinatra 站点作为跨两个 IP 的虚拟主机。我想防止 Nginx 不得不提供静态文件,因为我注意到一些延迟。

编辑:我已更改为 Nginx,但提供的答案很容易移植到 nginx。

rjk*_*rjk 6

Apache 仍将提供静态文件,但只会为它们提供一次。也许最简单的方法是配置 varnish 以侦听端口 80 的所有 IP 地址,并将 Apache 配置为侦听localhost:8000。然后配置 varnish 将它收到的所有请求转发给localhost:8000Apache 处理。

我会使用以下清漆配置:

# have varnish listen on port 80 (all addresses)
varnishd -a 0.0.0.0:80
Run Code Online (Sandbox Code Playgroud)

现在在您的vcl文件中:

backend default {
  .host = "localhost";
  .port = "8000";
}

sub vcl_recv {
  # add a unique header containing the client IP address
  set req.http.X-Orig-Forwarded-For = client.ip;

  # we're only handling static content for now so remove any
  # Cookie that was sent in the request as that makes caching
  # impossible.
  if (req.url ~ "\.(jpe?g|png|gif|ico|js|css)(\?.*|)$") {
    unset req.http.cookie;
  }
}

vcl_fetch {
  # if the backend server adds a cookie to all responses,
  # remove it from static content so that it can be cached.
  if (req.url ~ "\.(jpe?g|png|gif|ico|js|css)(\?.*|)$") {
    unset obj.http.set-cookie;
  }
}
Run Code Online (Sandbox Code Playgroud)

现在在您的 Apachehttpd.conf配置中,您希望 Apache 侦听localhost:8000并在同一地址上定义您的虚拟主机:端口

Listen 127.0.0.1:8000
NameVirtualHost 127.0.0.1:8000
Run Code Online (Sandbox Code Playgroud)

为每个网站创建一个<VirtualHost>节。在该节中,您需要告诉 ApacheExpires在所有静态内容上设置和缓存控制标头,以便 varnish 知道缓存它。

<VirtualHost 127.0.0.1:8000>
  ServerName www.our-example-domain.com

  # Set expires and cache-control headers on static content and
  # tell caches that the static content is valid for two years
  ExpiresActive on

  <FilesMatch "\.(js|css|ico|gif|png|jpe?g)$">
    ExpiresDefault "access plus 2 year"
    Header append Cache-Control "public"
  </FilesMatch>

  # ... the rest of your web site configuration ...
</VirtualHost>
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助。