Blog

Blog

PHODAL

Varnish Nginx配置失败原因

经历了之前配置Varnish Nginx 多站点配置的坑之后,写写这其中的过程。

Varnish Nginx多站点失败之80端口

或者你和我一样会遇到这样的错误

2014/09/21 11:16:08 [emerg] 32344#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2014/09/21 11:16:08 [emerg] 32344#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2014/09/21 11:16:08 [emerg] 32344#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2014/09/21 11:16:08 [emerg] 32344#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2014/09/21 11:16:08 [emerg] 32344#0: bind() to 0.0.0.0:80 failed (98: Address already in use)
2014/09/21 11:16:08 [emerg] 32344#0: still could not bind()

然后我检查了好几遍都没有发现错误的原因(ps:多个网站),于是只好一步步检查,最后发现了以下几个事实:

Varnish与Nginx rewrite会发生冲突,导致80端口被占用

如下面的例子

server {
  server_name phodal.com;
  rewrite ^(.*) http://www.phodal.com$1 permanent;
}

会继续占用80端口,这会导致你可能找不到真正失败的原因,这时我们需要去掉Nginx.conf中的重定向,而使用Varnish中的Rewrite,如

if (req.http.host ~ "^(www\.)?example\.com" && req.url~ "^/images/") {
  set req.http.host = "images.example.com";
  set req.url = regsub(req.url, "^/images/", "/");
}

可以将http://www.example.com/images/foo.jpg 重定向到 http://images.example.com/foo.jpg.。下面的例子便是都走向example.com

  set req.http.host = regsub(req.http.host, "^www\.example\.com$","phodal.com");

Varnish Nginx多站点失败之WP Super Cache

一个WP Super Cache的Wordpress的配置如下

set $cache_uri $request_uri;

   # POST requests and urls with a query string should always go to PHP
if ($request_method = POST) {
    set $cache_uri 'null cache';
}

if ($query_string != "") {
    set $cache_uri 'null cache';
}

     # Don't cache uris containing the following segments
if ($request_uri ~* "(/wp-admin/|/xmlrpc.php|/wp-(app|cron|login|register|mail).php|wp-.*.php|/feed/|index.php|wp-comments-popup.php|wp-links-opml.php|wp-locations.php|sitemap(_index)?.xml|[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {
    set $cache_uri 'null cache';
}

      # Don't use the cache for logged in users or recent commenters
if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_logged_in") {
    set $cache_uri 'null cache';
}

location = /favicon.ico { log_not_found off; access_log off; }

     # Use cached or actual file if they exists, otherwise pass request to WordPress
location / {
    try_files /wp-content/cache/supercache/$http_host/$cache_uri/index.html $uri $uri/ /index.php ;
    etag on;
    if (-f $request_filename/index.html){
        rewrite (.*) $1/index.html break;
    }
    if (-f $request_filename/index.php){
        rewrite (.*) $1/index.php;
    }
    if (!-f $request_filename){
        rewrite (.*) /index.php;
    }
}

于是对于这样的例子,我们似乎无法使用Varnish来Rewrite

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签