手动 4- linux配置varnish

本文详细介绍了在CentOS 6环境中快速安装及配置Varnish的过程,包括所需依赖软件的安装、Varnish配置文件的编写与调整等关键步骤,并提供了针对Magento系统的特别配置说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#############################################

centos 6 快速安装:

rpm --nosignature -i http://repo.varnish-cache.org/redhat/varnish-3.0/el6/noarch/varnish-release/varnish-release-3.0-1.el6.noarch.rpm

yum install varnish

#############################################

安装完成magento后,需要安装varnish


安装varnish:

1.
安装环境,其他软件,varnish需要这些软件的支持。
yum install -y automake autoconf libtool ncurses-devel libxslt groff pcre-devel pkgconfig  libedit*


2.
wget http://jaist.dl.sourceforge.net/project/pcre/pcre/8.34/pcre-8.34.zip


手动下载地址:http://sourceforge.net/projects/pcre/files/pcre/
安装pcre
unzip -o pcre-8.34.zip
cd pcre-8.34
./configure --prefix=/usr/local/pcre/
make
make install


3
安装varnish
wget http://repo.varnish-cache.org/source/varnish-3.0.4.tar.gz
tar zxvf varnish-3.0.4.tar.gz
cd varnish-3.0.4
export PKG_CONFIG_PATH=/usr/local/pcre/lib/pkgconfig/
./configure --prefix=/usr/local/varnish --enable-dependency-tracking --enable-debugging-symbols --enable-developer-warnings
make
make install
cp redhat/varnish.initrc  /etc/init.d/varnish  --varnish的启动脚本
cp redhat/varnish.sysconfig  /etc/sysconfig/varnish  --varnish配置文件
cp redhat/varnish_reload_vcl /usr/local/varnish/bin/ --此文件用于修改配置文件后重新加载,这样避免重启造成已缓存文件丢失



编辑文件:

vim  /etc/sysconfig/varnish

#Configuration file for varnish
#
# /etc/init.d/varnish expects the variable $DAEMON_OPTS to be set from this
# shell script fragment.
#

# Maximum number of open files (for ulimit -n)
NFILES=131072

# Locked shared memory (for ulimit -l)
# Default log size is 82MB + header
MEMLOCK=82000

# Maximum size of corefile (for ulimit -c). Default in Fedora is 0
# DAEMON_COREFILE_LIMIT="unlimited"

# Set this to 1 to make init script reload try to switch vcl without restart.
# To make this work, you need to set the following variables
# explicit: VARNISH_VCL_CONF, VARNISH_ADMIN_LISTEN_ADDRESS,
# VARNISH_ADMIN_LISTEN_PORT, VARNISH_SECRET_FILE, or in short,
# use Alternative 3, Advanced configuration, below
RELOAD_VCL=1

# This file contains 4 alternatives, please use only one.

## Alternative 1, Minimal configuration, no VCL
#
# Listen on port 6081, administration on localhost:6082, and forward to
# content server on localhost:8080. Use a fixed-size cache file.
#
#DAEMON_OPTS="-a :80 \
# -T 173.193.39.186:2000 \
# -u varnish -g varnish \
# -s file,/data/varnish/cache/varnish_cache.data,80G"
# -f /usr/local/varnish/etc/varnish/default.vcl

## Alternative 2, Configuration with VCL
#
# Listen on port 6081, administration on localhost:6082, and forward to
# one content server selected by the vcl file, based on the request. Use a
# fixed-size cache file.
#
#DAEMON_OPTS="-a :6081 \
# -T localhost:6082 \
# -f /etc/varnish/default.vcl \
# -u varnish -g varnish \
# -S /etc/varnish/secret \
# -s file,/var/lib/varnish/varnish_storage.bin,1G"


## Alternative 3, Advanced configuration
#
# See varnishd(1) for more information.
#
# 配置文件路径: # Main configuration file. You probably want to change it :)
VARNISH_VCL_CONF=/usr/local/varnish/etc/varnish/default.vcl
#
# # Default address and port to bind to
# # Blank address means all IPv4 and IPv6 interfaces, otherwise specify
# # a host name, an IPv4 dotted quad, or an IPv6 address in brackets.
# 默认监听端口:VARNISH_LISTEN_ADDRESS=
VARNISH_LISTEN_PORT=80
#
# 后台端口# Telnet admin interface listen address and port
VARNISH_ADMIN_LISTEN_ADDRESS=173.193.39.187
VARNISH_ADMIN_LISTEN_PORT=6088
#
# secrest 文件路径# Shared secret file for admin interface
VARNISH_SECRET_FILE=/usr/local/varnish/etc/varnish/secret
#
# # The minimum number of worker threads to start
VARNISH_MIN_THREADS=50
#
# # The Maximum number of worker threads to start
VARNISH_MAX_THREADS=1000
#
# # Idle timeout for worker threads
VARNISH_THREAD_TIMEOUT=120
#
# # Cache file location
# varnish 文件路径 VARNISH_STORAGE_FILE=/var/lib/varnish/varnish_storage.bin
VARNISH_STORAGE_FILE=/data/varnish/cache/varnish_cache.data
#
# # Cache file size: in bytes, optionally using k / M / G / T suffix,
# varnish分配的内存 # or in percentage of available disk space using the % suffix.
VARNISH_STORAGE_SIZE=6G
#
# # Backend storage specification
VARNISH_STORAGE="file,${VARNISH_STORAGE_FILE},${VARNISH_STORAGE_SIZE}"
#
# 过期时间 # Default TTL used when the backend does not specify one
VARNISH_TTL=864000000
#
# # DAEMON_OPTS is used by the init script. If you add or remove options, make
# # sure you update this section, too.
DAEMON_OPTS="-a ${VARNISH_LISTEN_ADDRESS}:${VARNISH_LISTEN_PORT} \
-f ${VARNISH_VCL_CONF} \
-T ${VARNISH_ADMIN_LISTEN_ADDRESS}:${VARNISH_ADMIN_LISTEN_PORT} \
-t ${VARNISH_TTL} \
-w ${VARNISH_MIN_THREADS},${VARNISH_MAX_THREADS},${VARNISH_THREAD_TIMEOUT} \
-u varnish -g varnish \
-S ${VARNISH_SECRET_FILE} \
-s ${VARNISH_STORAGE}"
#


## Alternative 4, Do It Yourself. See varnishd(1) for more information.
#
# DAEMON_OPTS=""

上面的配置文件,复制后注意后面的空格,譬如:-w ${VARNISH_MIN_THREADS},${VARNISH_MAX_THREADS},${VARNISH_THREAD_TIMEOUT} \   ,后面有空格会报错

如果您想用内存,而不想用磁盘,那么 

-s malloc,4G

那么把


-s ${VARNISH_STORAGE

改为上面

注意:

上面需要修改的为:VARNISH_ADMIN_LISTEN_ADDRESS 改为当前ip
VARNISH_STORAGE_SIZE=6G  按照您的需要改
VARNISH_TTL= 按照您的需要过期时间



/usr/local/varnish/etc/varnish/default.vcl:

include "include/header.vcl";
include "include/footer.vcl";

/usr/local/varnish/etc/varnish/include/header.vcl:
backend default {
  .host = "127.0.0.1";
  .port = "6081";
  .connect_timeout = 6000s;
  .first_byte_timeout = 6000s;
  .between_bytes_timeout = 6000s;
}

backend weike {
     .host = "www.tomorrowtop.net";
     .port = "6001";
}

backend phpmyadmin {
     .host = "173.192.59.7";
     .port = "6002";
}

backend nagios {
     .host = "173.192.59.2";
     .port = "6003";
}

backend faspeed {
     .host = "www.faspeed.com";
     .port = "6004";
}

backend tomtopblog {
     .host = "blog.tomtop.com";
     .port = "6004";
}


backend tomtopcnblog {
     .host = "cnblog.tomtop.com";
     .port = "6004";
}


#acl purge {
#   "10.12.167.130";
#}


sub vcl_recv {
	
	#如果host为www.example.com,设置后端服务器为www,(?i)表示匹配模式为不区分大小写
     if (req.http.host ~ "(?i)^(img2.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(tomtop-auction.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(tomtop-au.)?tomtop.com$"
	 
	 || req.http.host ~ "(?i)^(tomtop-game.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(tomtop-shop.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(homegarden2012.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(tomtop-sales.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(usbempire.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(tomtop-home.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(tomtop-digital.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(tomtop-wholesaler.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(tomtop-w.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(tomtop-uk.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(antiquechina2009.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(tomtop-deals.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(tomorrowhome.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(ttmallzone365.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(tomorrowtop.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(tomtop-usa.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(ttstoreusa.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(tomtop-mall.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(tomorrowyes.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(costcobuy.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(tomorrowokla.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(addstore.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(newgaga.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(newmango.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(lalayes.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(dudustory.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(buyonline315.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(bluebetter.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(tootooup.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(ilastone.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(kokoyesgo.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(anforme.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(smartlife2013.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(dodotech.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(7colorstore.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(topestore360.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(usbcity888.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(dadidashop.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(duoduobox.)?tomtop.com$"
	 || req.http.host ~ "(?i)^(anderlink.)?tomtop.com$"
	
	 ) {
         # set req.http.host = "127.0.0.1";
          set req.backend = default;
     #如果为images.example.com,设置后端服务器为images
     } elsif (req.http.host ~ "(?i)^www.tomorrowtop.net$") {
          set req.backend = weike;
		  return (pass);
	} elsif (req.http.host ~ "(?i)^blog.tomtop.com$") {
          set req.backend = tomtopblog;
		  return (pass);
		  
	} elsif (req.http.host ~ "(?i)^cnblog.tomtop.com$") {
          set req.backend = tomtopcnblog;
		  return (pass);
		  
	 } elsif ((req.http.host ~ "(?i)^www.faspeed.com$")||(req.http.host ~ "(?i)^faspeed.com$")) {
          set req.backend = faspeed;
		  return (pass);
		  
	 } elsif (req.http.host ~ "(?i)^173.192.59.7$") {
          set req.backend = phpmyadmin;
		 # set req.http.host = "127.0.0.1";
		  return (pass);
	 } elsif (req.http.host ~ "(?i)^173.192.59.2$") {
          set req.backend = nagios;
                  return (pass);
		
     } else {
          error 404 "Unknown virtual host";
     }
	 
    remove req.http.X-real-ip;  
    set req.http.X-real-ip = client.ip;  
    set req.http.X-Forwarded-For = client.ip;  

    if (req.request == "GET" && (req.url ~ "\?imgurl.*\.(png|jpg|jpeg|gif|css)$")) {
       return (lookup);
    }
	
	if (req.request == "GET" && (req.url ~ "\.css$" || req.url ~ "print.css")) {
       return (lookup);
    }
    

#purge all
    if (req.request == "BAN") {
        #if (!client.ip ~ purge) {
        #    error 405 "Not allowed.";
        #}
        ban("req.url ~ " + req.url );
        #error 200 "Purged.";
		return (lookup);
    }

    if (req.request == "POST") {
        return (pass);
    }

    if (req.http.Authorization) {
        /* Not cacheable by default */
        return (pass);
    }
	
	#if (req.url == "/") {
    #    return (pass);
    #}

    if (req.url ~ "^/tomtopadmin" || req.url ~ "^/index.php/tomtopadmin") {
        return (pass);
    }
#we should not cache any page for checkout and customer modules
    if (req.request == "GET" && (req.url ~ "^/checkout" || req.url ~ "^/customer" || req.url ~ "^/varnish" || req.url ~ "^/vynamic")) {
        return (pass);
    }
    
# normalize Accept-Encoding to reduce vary
    if (req.http.Accept-Encoding) {
        if (req.http.User-Agent ~ "MSIE 6") {
            unset req.http.Accept-Encoding;
        } elsif (req.http.Accept-Encoding ~ "gzip") {
            set req.http.Accept-Encoding = "gzip";
        } elsif (req.http.Accept-Encoding ~ "deflate") {
            set req.http.Accept-Encoding = "deflate";
        } else {
            unset req.http.Accept-Encoding;
        }
    }


    return (pass);
}

/usr/local/varnish/etc/varnish/include/footer.vcl:

sub vcl_hash {
	
    if (req.http.host) {
        hash_data(req.http.host);
    } else {
        hash_data(server.ip);
    }
	
	if (req.url ~ "\?acc=.*" && (req.url !~ "\?acc=.*&.*" && req.url !~ "\?.*&acc=.*" ) ) {
		hash_data(regsub(req.url, "\?.*", ""));
    }elseif (req.url ~ "\?aid=.*" && (req.url !~ "\?aid=.*&.*" && req.url !~ "\?.*&aid=.*" ) ) {
		hash_data(regsub(req.url, "\?.*", ""));
	}elseif(req.url ~ "\?aid=.*&bannerid=.*"){
		hash_data(regsub(req.url, "\?.*", ""));
	}else {
       hash_data(req.url);
    }
	
    #hash_data(req.url);
    if (regsub(req.http.Cookie, ".*currency=([A-Z]*).*", "\1") ~ "=") {
        hash_data("USD");
    } else {
        hash_data(regsub(req.http.Cookie, ".*currency=([A-Z]*).*", "\1"));
    }
	
	if (regsub(req.http.Cookie, ".*country=([A-Z]*).*", "\1") ~ "=") {
        hash_data("US");
    } else {
        hash_data(regsub(req.http.Cookie, ".*country=([A-Z]*).*", "\1"));
    }

    return (hash);
}

sub vcl_hit {
    if (req.request == "BAN") {
        purge;
        error 200 "Hit Purged.";
    }

    return (deliver);
}

sub vcl_miss {
    if (req.request == "BAN") {
       #purge;
       #error 200 "Miss Purged.";
    }

    return (fetch);
}

sub vcl_fetch {
	
    set beresp.ttl = 86400 s;  // default cache 12 hours
	
    if (req.url ~ "^/(\?|$)") {
        return (deliver);
    }
    if (beresp.status == 302) {
        return (hit_for_pass);
    }
	
	#Saint mode
    if (beresp.status == 500 || beresp.status == 502 || beresp.status == 503 || beresp.status == 504) { 
	    set beresp.saintmode = 5m;
	    return (restart); 
    }

	#Fix a strange problem: HTTP 301 redirects to the same page sometimes go in$
    if (beresp.http.Location == "http://" + req.http.host + req.url) {
        if (req.restarts > 2) {
            unset beresp.http.Location;
		#set beresp.http.X-Restarts = req.restarts;
        } else {
            return (restart);
        }
    }
    return (hit_for_pass);
}

sub vcl_deliver {
    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT";
    } else {
        set resp.http.X-Cache = "MISS";
    }   
    return (deliver);
}

sub vcl_error {
    set obj.http.Content-Type = "text/html; charset=utf-8";
    set obj.http.Retry-After = "5";
    synthetic {"
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  </head>
  <script>
      function to_home() {
          window.location.href = "http://www.tomtop.com";
      }
  </script>
  <body>
    <center>
    Oops! Something unexpected happens. Our support team has been notified. <br/>
    Please try again(by refleshing the page) shortly or call our customer service or <a href="http://www.tomtop.com/webmaster">report a site bug for us</a>.<br/>
    Will redirect to <a href="http://www.tomtop.com">home</a> page in 10 seconds.
    </center>
    <script>
        window.setTimeout('to_home()', 5000);
    </script>

  </body>
</html>
"};
    return (deliver);
}





#新建文件,用来做缓存输出。
mkdir /data/varnish/cache

touch /data/varnish/cache/varnish_cache.data

groupadd varnish
useradd -g varnish varnish  
uuidgen >/usr/local/varnish/etc/varnish/secret
chmod 644 /usr/local/varnish/etc/varnish/secret
ln  /usr/local/varnish/sbin/varnishd   /usr/sbin/varnishd 
/etc/init.d/varnish restart





4

下载magento插件varnish,

由于magento的varnish在1.8是不好用的,因为1.8中的加入购物链接存在form_key,所以会不好用,下面这个链接修复了这个功能:

http://download.youkuaiyun.com/detail/terry_water/6974513

安装

完成后,在后台打开varnish即可,

参考图片:




5
覆盖varnish.vcf到(需要编辑ip)
/usr/local/varnish/etc/varnish/default.vcl
下载地址:http://download.youkuaiyun.com/detail/terry_water/6970943

设置nginx的端口改为90
重启nginx


6
启动varnish
/usr/local/varnish/sbin/varnishd -f /usr/local/varnish/etc/varnish/default.vcl -s file, </data/varnish/cache/varnish_cache.data> ,1G -T 121.199.39.117:2000 -a :80


注意,网站配置一定是域名根目录,不要加子域名。


7注意:

在配置的时候,因为varnish指向的是12.0.0.1,所以,在配置nginx的时候,需要把127.0..0.1配置进去。

server_name 127.0.0.1,121.199.39.177;

如果出现加入购物车失败,则:

system-->configuration

web-->session cookie manager

cookie lifetime:36000000


8

如果想开启调试功能:

那么:

在magento后台开启:







如果多次出现miss的情况,请清空浏览器cookie,重新试


9

备注:

magento1.8安装后,会出现无法加入购物车的现象,这是因为1.8加入了form_key,需要是为了防止 XSS attacks

可以通过ajax异步获取form_key,加入,也可以通过下面的方法:

https://bitbucket.org/supportdesk_nl/turpertine-formkey-workaround/downloads

插件下载地址为:

http://download.youkuaiyun.com/detail/terry_water/6973299


其他:

https://github.com/nexcess/magento-turpentine/issues/345




10

Varnish-3.0.4 error.: 

Leaving directory `/root/lnmp/src/varnish-3.0.4/bin/varnishadm'
 报错后,安装3.0.3的步骤

varnishadm.c:48:33: error: editline/readline.h:No such file or directory
varnishadm.c:Infunction'cli_write':
varnishadm.c:76: warning: implicit declaration of function'rl_callback_handler_remove'
varnishadm.c:76: warning: nested extern declaration of 'rl_callback_handler_remove'
varnishadm.c:Infunction'send_line':
varnishadm.c:179: warning: implicit declaration of function'add_history'
varnishadm.c:179: warning: nested extern declaration of 'add_history'
varnishadm.c:Infunction'varnishadm_completion':
varnishadm.c:216: warning: implicit declaration of function'rl_completion_matches'
varnishadm.c:216: warning: nested extern declaration of 'rl_completion_matches'
varnishadm.c:216: warning: assignment makes pointer from integer without a cast
varnishadm.c:Infunction'pass':
varnishadm.c:233: error:'rl_already_prompted' undeclared (first use in this function)
varnishadm.c:233: error:(Each undeclared identifier is reported only once
varnishadm.c:233: error:for each function it appears in.)
varnishadm.c:235: warning: implicit declaration of function'rl_callback_handler_install'
varnishadm.c:235: warning: nested extern declaration of 'rl_callback_handler_install'
varnishadm.c:239: error:'rl_attempted_completion_function' undeclared (first use in this function)
varnishadm.c:300: warning: implicit declaration of function'rl_forced_update_display'
varnishadm.c:300: warning: nested extern declaration of 'rl_forced_update_display'
varnishadm.c:303: warning: implicit declaration of function'rl_callback_read_char'
varnishadm.c:303: warning: nested extern declaration of 'rl_callback_read_char'
make[3]:***[varnishadm-varnishadm.o]Error1
make[3]:Leaving directory `/root/lnmp/src/varnish-3.0.4/bin/varnishadm'
make[2]: *** [all-recursive] Error 1
make[2]: Leaving directory `/root/lnmp/src/varnish-3.0.4/bin'
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory `/root/lnmp/src/varnish-3.0.4'
make:***[all]Error2

Error not find a solution, varnish-3.0.3

wget http://repo.varnish-cache.org/source/varnish-3.0.3.tar.gz
tar xzf varnish-3.0.3.tar.gz
cd varnish-3.0.3
export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
./configure --prefix=/usr/local/varnish --enable-debugging-symbols --enable-developer-warnings --enable-dependency-tracking --with-jemalloc
make && make install
/usr/bin/install -m 755./redhat/varnish.initrc /etc/init.d/varnish
/usr/bin/install -m 644./redhat/varnish.sysconfig /etc/sysconfig/varnish
/usr/bin/install -m 755./redhat/varnish_reload_vcl /usr/local/varnish/bin
useradd -M -s /sbin/nologin varnish

ln -s /usr/local/varnish/sbin/varnishd /usr/sbin/
ln -s /usr/local/varnish/bin/varnish_reload_vcl /usr/bin/
ln -s /usr/local/varnish/bin/varnishadm /usr/bin/

chkconfig --add varnish
chkconfig varnish on

Generate varnish management key:

uuidgen >/usr/local/varnish/etc/varnish/secret
chmod 644/usr/local/varnish/etc/varnish/secret

Modify the varnish boot configuration:

sed -i "s@^VARNISH_VCL_CONF=/etc/varnish/default.vcl@#VARNISH_VCL_CONF=/etc/varnish/default.vcl\nVARNISH_VCL_CONF=/usr/local/varnish/etc/varnish/linuxeye.vcl@"/etc/sysconfig/varnish
sed -i "s@^VARNISH_LISTEN_PORT=6081@#VARNISH_LISTEN_PORT=6081\nVARNISH_LISTEN_PORT=80@"/etc/sysconfig/varnish
sed -i "s@^VARNISH_SECRET_FILE=/etc/varnish/secret@#VARNISH_SECRET_FILE=/etc/varnish/secret\nVARNISH_SECRET_FILE=/usr/local/varnish/etc/varnish/secret@"/etc/sysconfig/varnish
sed -i "s@^VARNISH_STORAGE_FILE=/var/lib/varnish/varnish_storage.bin@#VARNISH_STORAGE_FILE=/var/lib/varnish/varnish_storage.bin\nVARNISH_STORAGE_FILE=/usr/local/varnish/var/varnish_storage.bin@"/etc/sysconfig/varnish
sed -i "s@^VARNISH_STORAGE_SIZE.*@VARNISH_STORAGE_SIZE=150M@"/etc/sysconfig/varnish
sed -i "s@^VARNISH_STORAGE=.*@VARNISH_STORAGE=\"malloc,\${VARNISH_STORAGE_SIZE}\"@"/etc/sysconfig/varnish

If your server has multiple logic processor, also can do the following settings: &rdquo parameter, 
/etc/sysconfig/varnish can also add custom; -p parameter “ way to add, such as:

DAEMON_OPTS="-a ${VARNISH_LISTEN_ADDRESS}:${VARNISH_LISTEN_PORT} \
             -f ${VARNISH_VCL_CONF} \
             -T ${VARNISH_ADMIN_LISTEN_ADDRESS}:${VARNISH_ADMIN_LISTEN_PORT} \
             -t ${VARNISH_TTL} \
             -w ${VARNISH_MIN_THREADS},${VARNISH_MAX_THREADS},${VARNISH_THREAD_TIMEOUT} \
             -u varnish -g varnish \
             -S ${VARNISH_SECRET_FILE} \
             -s ${VARNISH_STORAGE} \
             -p thread_pools=2"#Here to add items

Varnish started to run in the background, and return to command state. Of note, the Varnish runtime will also start the two process, a main course, a child process, if the child process problems, the main process will produce a sub process.

The VCL configuration
/usr/local/varnish/etc/varnish/linuxeye.vcl.sh

#The backend defines a name for the webserver backend host, “.Host” specify the backend host IP address or domain name, “.Port” specify the backend host service port. 
backend webserver {.host ="127.0.0.1";.port ="8080";}#Call vcl_recv
sub vcl_recv {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;}}#If the request is not of type GET, HEAD, PUT, POST, TRACE, OPTIONS, DELETE, enter pipe mode. Note that there is “ & & ” relationship
      if(req.request !="GET"&&
      req.request !="HEAD"&&
      req.request !="PUT"&&
      req.request !="POST"&&
      req.request !="TRACE"&&
      req.request !="OPTIONS"&&
      req.request !="DELETE"){return(pipe);}#If the request is not of type GET and HEAD, then enter pass mode
    if(req.request !="GET"&& req.request !="HEAD"){return(pass);}if(req.http.Authorization|| req.http.Cookie){return(pass);}#The linuxeye.com domain name caching acceleration, this is the concept of a universal domain, all at the end of the linuxeye.com domain name cache
    if(req.http.host ~"^(.*).linuxeye.com"){set req.backend = webserver;}#On.Jsp,.Do, and PHP end with? URL, direct read content from the backend server
    if(req.url ~"\.(jsp|do|php)($|\?)"){return(pass);}else{return(lookup);}}

sub vcl_pipe {return(pipe);}

sub vcl_pass {return(pass);}

sub vcl_hash {
    hash_data(req.url);if(req.http.host){
        hash_data(req.http.host);}else{
        hash_data(server.ip);}return(hash);}

sub vcl_hit {return(deliver);}

sub vcl_miss {return(fetch);}#For the request type is GET, and the requested URL contains upload, then caching, cache time is 300 seconds, 5 minutes
sub vcl_fetch {if(req.request =="GET"&& req.url ~"^/upload(.*)$"){set beresp.ttl =300s;}if(req.request =="GET"&& req.url ~"\.(png|gif|jpg|jpeg|bmp|swf|css|js|html|htm|xsl|xml|pdf|ppt|doc|docx|chm|rar|zip|ico|mp3|mp4|rmvb|ogg|mov|avi|wmv|txt)$"){
      unset beresp.http.set-cookie;set beresp.ttl =30d;}return(deliver);}#The following is to add a Header mark, to determine whether the cache hit
sub vcl_deliver {if(obj.hits >0){set resp.http.X-Cache="HIT from demo.linuxeye.com";}else{set resp.http.X-Cache="MISS from demo.linuxeye.com";}return(deliver);}#Use vcl_error to a custom error page
sub vcl_error {set obj.http.Content-Type="text/html; charset=utf-8";set obj.http.Retry-After="5";
    synthetic {"
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>"}+ obj.status +" "+ obj.response +{"</title>
  </head>
  <body>
    <h1>Error "}+ obj.status +" "+ obj.response +{"</h1>
    <p>"}+ obj.response +{"</p>
    <h3>Guru Meditation:</h3>
    <p>XID: "}+ req.xid +{"</p>
    <hr>
    <p>Varnish cache server</p>
  </body>
</html>
"};return(deliver);}

sub vcl_init {return(ok);}

sub vcl_fini {return(ok);}

Check the VCL configuration is correct:

service varnish configtest

Or

varnishd -C -f /usr/local/varnish/etc/varnish/linuxeye.vcl

Start varnish:

service varnish start

Check the varnish status:

service varnish status

The dynamic loading VCL configuration:

service varnish reload

Stop varnish:

service varnish stop

80 port to view the current varnish monitoring:

# netstat -tpln | grep :80
tcp        000.0.0.0:800.0.0.0:*                   LISTEN      15249/varnishd
tcp        000.0.0.0:80800.0.0.0:*                   LISTEN      19468/nginx
tcp        00:::80:::*                        LISTEN      15249/varnishd

To view the varnish process:

# ps -ef | grep varnishd | grep -v grep
root     152481011:47?00:00:00/usr/sbin/varnishd -P /var/run/varnish.pid -a :80-f /usr/local/varnish/etc/varnish/linuxeye.vcl -T 127.0.0.1:6082-t 120-w 50,1000,120-u varnish -g varnish -S /usr/local/varnish/etc/varnish/secret -s malloc,150M
varnish  1524915248011:47?00:00:00/usr/sbin/varnishd -P /var/run/varnish.pid -a :80-f /usr/local/varnish/etc/varnish/linuxeye.vcl -T 127.0.0.1:6082-t 120-w 50,1000,120-u varnish -g varnish -S /usr/local/varnish/etc/varnish/secret -s malloc,150M

Varnish access log 
varnishncsa can use NCSA common log format (NCSA Common Log Format) HTTP request record to the log file.

/usr/bin/install -m 755./redhat/varnishncsa.initrc /etc/init.d/varnishncsa
chmod +x /etc/init.d/varnishncsa
chkconfig varnishncsa on
mkdir -p /usr/local/varnish/logs

Edit the varnishncsa boot configuration

ln -s /usr/local/varnish/bin/varnishncsa /usr/bin
sed -i 's@^logfile.*@logfile="/usr/local/varnish/logs/varnishncsa.log"@'/etc/init.d/varnishncsa

Start varnishncsa:

service varnishncsa start

The use of logrotate log file (polling day polling):

cat >/etc/logrotate.d/varnish << EOF
/usr/local/varnish/logs/varnishncsa.log {
daily
rotate 5
missingok
dateext
compress
notifempty
sharedscripts
postrotate
    [-e /var/run/varnishncsa.pid ]&& kill -USR1 \`cat /var/run/varnishncsa.pid\`
endscript
}
EOF

Log polling debug test:

logrotate -df /etc/logrotate.d/varnish


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值