文档
一个 项目,由 ZeroSSL 出品

handle

评估一组指令,这些指令与其他同级嵌套的 handle 块互斥。

换句话说,当连续出现多个 handle 指令时,只会评估第一个匹配handle 块。没有匹配器的 handle 行为类似于回退路由。

handle 指令根据其匹配器通过指令排序算法进行排序。 handle_path 指令是一种特殊情况,它与带有路径匹配器的 handle 具有相同的优先级。

如果需要,Handle 块可以嵌套。只有 HTTP 处理程序指令可以在 handle 块内部使用。

语法

handle [<matcher>] {
	<directives...>
}
  • <directives...> 是 HTTP 处理程序指令或指令块的列表,每行一个,就像在 handle 块外部使用一样。

类似指令

还有其他指令可以包装 HTTP 处理程序指令,但每种指令都有其用途,具体取决于您想要表达的行为

  • handle_path 的作用与 handle 相同,但它会在运行其处理程序之前从请求中剥离前缀。

  • handle_errors 类似于 handle,但仅在 Caddy 在请求处理期间遇到错误时调用。

  • routehandle 一样包装其他指令,但有两个区别

    1. route 块彼此不互斥,
    2. route 中的指令不会被重新排序,如果您需要,可以提供更多控制。

示例

使用静态文件服务器处理 /foo/ 中的请求,并使用反向代理处理其他请求

example.com {
	handle /foo/* {
		file_server
	}

	handle {
		reverse_proxy 127.0.0.1:8080
	}
}

您可以在同一个站点中混合使用 handlehandle_path,它们仍然会彼此互斥

example.com {
	handle_path /foo/* {
		# The path has the "/foo" prefix stripped
	}

	handle /bar/* {
		# The path still retains "/bar"
	}
}

您可以嵌套 handle 块以创建更复杂的路由逻辑

example.com {
	handle /foo* {
		handle /foo/bar* {
			# This block only matches paths under /foo/bar
		}

		handle {
			# This block matches everything else under /foo/
		}
	}

	handle {
		# This block matches everything else (acts as a fallback)
	}
}