Nginx Cache按域名存放

From http://blog.meiu.cn/nginx-proxy_cache.html

在Nginx或者Tengine默认的cache都是按照一定的hash算法出来的,如果需要擦除某个域名下的全站cache,用purge只能通过遍历所有的url在实现,效率肯定是很低的。那么如果把cache按照域名存放那么清空起来就很快了。

修改 src/http/ngx_http_file_cache.c

在文件头声明函数部分加

static ngx_int_t ngx_http_file_cache_domain(ngx_http_request_t *r,
ngx_path_t *path);

函数实现
static ngx_int_t ngx_http_file_cache_domain(ngx_http_request_t *r,ngx_path_t *path)
{
    ngx_http_cache_t    *c;
    u_char              *pathname,*pos;
    size_t              i;
    ngx_str_t           *key,domain;

    c = r->cache;
    key = c->keys.elts;

    domain.len  = key[0].len;
    domain.data = ngx_pstrdup(r->pool,& key[0]);
    pos = (u_char *) ngx_strchr(domain.data,'/');
    if(pos){
        *pos = '\0';
        domain.len = ngx_strlen(domain.data);

        pathname = path->name.data;
        i = path->name.len+1;
        pathname[i-1] = '/';
        ngx_memcpy(&pathname[i],domain.data,domain.len);
        path->name.len = i + domain.len;
    }
    return NGX_OK;
}

然后修改 ngx_http_file_cache_name 函数
static ngx_int_t
ngx_http_file_cache_name(ngx_http_request_t *r, ngx_path_t *path)
{
    u_char            *p;
    ngx_http_cache_t  *c;
    size_t            pathlen;

    c = r->cache;
    pathlen = path->name.len;

    ngx_http_file_cache_domain(r,path);
    
      c->file.name.len = path->name.len + 1 + path->len
                       + 2 * NGX_HTTP_CACHE_KEY_LEN;
      c->file.name.data = ngx_pnalloc(r->pool, c->file.name.len + 1);
      
    if (c->file.name.data == NULL) {
            return NGX_ERROR;
    }

    ngx_memcpy(c->file.name.data, path->name.data, path->name.len);

    p = c->file.name.data + path->name.len + 1 + path->len;
    p = ngx_hex_dump(p, c->key, NGX_HTTP_CACHE_KEY_LEN);
    *p = '\0';
    
    ngx_create_hashed_filename(path, c->file.name.data, c->file.name.len);
    ngx_log_debug1(NGX_LOG_DEBUG_HTTP, r->connection->log, 0,
               "cache file: \"%s\"", c->file.name.data);
    
    path->name.len = pathlen;
    
    return NGX_OK;
}

重新编译就可以了

标签:Linux, Nginx, Cache

评论已关闭