文件
a 專案

handle

評估一組指令,這些指令與同層級巢狀結構中的其他 handle 區塊互斥。

換句話說,當多個 handle 指令依序出現時,只有第一個匹配handle 區塊會被評估。沒有匹配器的 handle 就像一個後備路由。

handle 指令根據其匹配器依 指令排序演算法 排序。handle_path 指令是一個特例,其排序優先順序與帶有路徑匹配器的 handle 相同。

handle 區塊可以根據需要巢狀化。只有 HTTP 處理器指令可以用在 handle 區塊內。

語法

handle [<matcher>] {
	<directives...>
}
  • <指令...> 是一個 HTTP 處理器指令或指令區塊的列表,每行一個,就像在 handle 區塊外部使用一樣。

相似指令

還有其他可以包裝 HTTP 處理器指令的指令,但每個指令都有其用途,取決於您想要傳達的行為。

  • handle_path 的作用與 handle 相同,但在運行其處理器之前,它會從請求中剝離前綴。

  • handle_errors 類似於 handle,但僅在 Caddy 在請求處理期間遇到錯誤時才會被調用。

  • route 包裝其他指令,就像 handle 一樣,但有兩個區別

    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)
	}
}