清漆:如果响应为404,则重写URL [英] Varnish: Rewrite a URL if response is 404

查看:95
本文介绍了清漆:如果响应为404,则重写URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇,如果在Varnish 2.1.5中,如果响应为404,是否可以重写URL?

I'm curious if there is a way rewrite a URL if response is a 404, in Varnish 2.1.5?

例如.我想提取一个URL,该URL可能存在也可能不存在.如果URL不存在,我想重写URL,然后尝试新的URL.

For example. I'd like to pull up a URL, which may or may not exist. If the URL doesn't exist, I'd like to do a URL rewrite and try the new URL instead.

我是Varnish的新手,并不完全了解请求的生命周期(如果有人认识这篇文章的人,请分享).

I'm new to Varnish and don't completely understand the lifecycle of a request (if anyone knows a guy of article explaining this, please share).

我尝试设置一些变量和请求标头,并检查res.status,但它们似乎在生命周期和页面404s的任何地方都丢失了:

I've tried setting some variables and request headers, and checking res.status but they seem to get lost someplace in the lifecycle and the page 404s anyways:

if (req.http.cookie ~ "lang_pref"
      && resp.status == 404
      && req.url ~ "^\/(en|fr|de)(\/.*)?$"
      ) {
    set resp.http.Location = "https://" req.http.host regsub(req.url, "^\/(en|fr|de)\/","/");
  }

该用例适用于翻译后的网站.例子

The use case is for a translated site. Example

Website.com/french/page可能存在或不存在 如果/French/page回应为404 然后尝试/page代替 如果/page不存在 然后是404

Website.com/french/page may or may not exist If /French/page responds with a 404 Then try /page instead If /page doesn't exist Then 404

推荐答案

我正在将其作为答案,否则它将显得很愚蠢. 请记住,永久移动了301,而临时移动了302.

I am writing this as an answer or it will look goofy as a comment. Keep in mind that 301 is permanently moved and 302 is temporarily moved.

您还可以像在帖子中一样调整使用正则表达式.

You can also adjust to use regex as you did in your post.

sub vcl_recv {
    if (req.url ~ "^/old/page") {
        return (synth(301, "/new/page"));
    }
    if (req.url ~ "^/this/oldPage") {
        return (synth(302, "/this/newPage"));
    }
}

sub vcl_synth {
    if (resp.status == 301 || resp.status == 302) {
        set resp.http.location = resp.reason;
        set resp.reason = "Moved";
        return (deliver);
    }
}

更新:解决评论.

sub vcl_error { 
  if (obj.status == 404) { 
  set obj.status = 301; 
  set obj.http.Location = obj.response; 
  return (deliver);

这篇关于清漆:如果响应为404,则重写URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆