Cloudflare Transform Rules でセキュリティヘッダーを設定する
Cloudflare の Transform Rules を使って、全レスポンスにセキュリティヘッダーを追加した。コード変更なしでヘッダーを付与できるので、静的サイトとの相性がいい。
設定したヘッダー
| ヘッダー | 値 | 目的 |
|---|---|---|
| X-Content-Type-Options | nosniff | MIME タイプスニッフィングの防止 |
| X-Frame-Options | DENY | クリックジャッキング防止 |
| Referrer-Policy | strict-origin-when-cross-origin | リファラー情報の制御 |
| Permissions-Policy | camera=(), microphone=(), geolocation=() | ブラウザ API の制限 |
| X-XSS-Protection | 1; mode=block | XSS フィルターの有効化 |
Terraform での設定
Cloudflare Provider v5 では cloudflare_ruleset リソースを使う。
resource "cloudflare_ruleset" "security_headers" {
zone_id = var.zone_id
name = "Security Headers"
kind = "zone"
phase = "http_response_headers_transform"
rules = [
{
action = "rewrite"
expression = "true"
description = "Add security headers"
enabled = true
action_parameters = {
headers = {
"X-Content-Type-Options" = {
operation = "set"
value = "nosniff"
}
}
}
},
]
}
expression = "true" で全リクエストに適用される。
確認
curl -sI https://ota2000.com | grep -i x-content-type
# x-content-type-options: nosniff
Transform Rules ならアプリケーションコードに手を入れずにヘッダーを追加できる。Terraform で管理しておけば設定内容も一目で分かる。