文件
一個 專案

handle

評估一組指令,這些指令與同層嵌套中的其他 handle 區塊互斥。

換句話說,當多個 handle 指令按順序出現時,只會評估第一個符合handle 區塊。沒有比對器的 handle 會像後備路由一樣運作。

handle 指令會根據其比對器,依照 指令排序演算法 排序。handle_path 指令是一個特例,其排序優先權與具有路徑比對器的 handle 相同。

如有需要,可以巢狀 handle 區塊。在 handle 區塊內只能使用 HTTP 處理器指令。

語法

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

類似指令

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

  • handle_path 的功能與 handle 相同,但它會在執行處理器之前從要求中移除一個前綴。

  • handle_errorshandle 類似,但只有在 Caddy 在要求處理期間遇到錯誤時才會呼叫。

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

    1. route 區塊不會彼此互斥,
    2. 路徑中的指令不會重新排序,讓您在需要時擁有更多控制權。

範例

使用靜態檔案伺服器處理 /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)
	}
}