§設定 gzip 編碼
Play 提供了一個 gzip 篩選器,可用於 gzip 回應。
§啟用 gzip 篩選器
若要啟用 gzip 篩選器,請將篩選器新增至 application.conf
play.filters.enabled += "play.filters.gzip.GzipFilter"
§設定 gzip 篩選器
gzip 濾器支援少數的調整組態選項,這些選項可以從 application.conf
中組態。如需查看可用的組態選項,請參閱 Play 濾器 reference.conf
。
§壓縮層級
你可以使用 play.filters.gzip.compressionLevel
來組態壓縮層級。值必須介於 -1
和 9
(含)之間,且遵循 java.util.zip.Deflater
定義的語意。例如,預設組態為 -1
,這是 預設壓縮層級,而 9
是 最佳壓縮。例如
play.filters.gzip.compressionLevel = 9
§控制要壓縮哪些回應
你可以透過 application.conf
來根據回應的內容類型控制要壓縮哪些回應,以及不壓縮哪些回應。
play.filters.gzip {
contentType {
# If non empty, then a response will only be compressed if its content type is in this list.
whiteList = [ "text/*", "application/javascript", "application/json" ]
# The black list is only used if the white list is empty.
# Compress all responses except the ones whose content type is in this list.
blackList = []
}
}
作為一個更具彈性的替代方案,你可以使用 gzip 濾器本身的 shouldGzip
參數,它接受一個將要求標頭和回應標頭作為函數傳遞給布林值。
例如,以下程式碼只會壓縮 HTML 回應
- Scala
-
new GzipFilter( shouldGzip = (request: RequestHeader, response: Result) => response.body.contentType.exists(_.startsWith("text/html")) )
- Java
-
GzipFilterConfig gzipFilterConfig = new GzipFilterConfig(); GzipFilter gzipFilter = new GzipFilter( gzipFilterConfig.withShouldGzip( (BiFunction<Http.RequestHeader, Result, Object>) (req, res) -> res.body().contentType().orElse("").startsWith("text/html")), materializer);
下一頁:組態安全性標頭
在這個文件當中發現錯誤嗎?此頁面的原始程式碼可以在 這裡 找到。在閱讀 文件指南 後,請隨時提交一個 pull request。有問題或建議要分享嗎?請前往 我們的社群論壇 與社群展開對話。