varnish 301 跳转 到 www

How to redirect non-www URLs to www in Varnish

If a website's canonical URL has www, it is desirable, as a good SEO practice, to redirect the non-www URLs to www. That is, if the canonical URL is www.example.com, example.com should be redirected to www.example.com. How to do this when Varnish is listening on port 80 as a reverse HTTP proxy is given below in this post.

Solution

For Varnish 3.0

Add the following code in the file, /etc/varnish/default.vcl,

sub vcl_recv {
 if (req.http.host == "example.com") { 
set req.http.host = "www.example.com";
 error 750 "http://" + req.http.host + req.url; 
} 
}
 sub vcl_error {
 if (obj.status == 750) { 
set obj.http.Location = obj.response; set obj.status = 301;
return(deliver);
 } }


In the above code, you need to replace the two occurrences of example.com with the domain name of your website.

For Varnish 4.0

There are changes in VCL for Varnish 4.0, and the code to be added to /etc/varnish/default.vcl is,

sub vcl_recv {
 if (req.http.host ~ "^example.com") {
 return (synth (750, "")); 
} }

 sub vcl_synth {
 if (resp.status == 750) {
 set resp.status = 301;
 set resp.http.Location = "http://www.example.com" + req.url; return(deliver); 
} }


As mentioned before, the two occurrences of example.com in the above code need to be replaced with the domain name of your website.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值