Cloudflare Transform Rules でセキュリティヘッダーを設定する

Cloudflare の Transform Rules を使って、全レスポンスにセキュリティヘッダーを追加した。コード変更なしでヘッダーを付与できるので、静的サイトとの相性がいい。

設定したヘッダー

ヘッダー目的
X-Content-Type-OptionsnosniffMIME タイプスニッフィングの防止
X-Frame-OptionsDENYクリックジャッキング防止
Referrer-Policystrict-origin-when-cross-originリファラー情報の制御
Permissions-Policycamera=(), microphone=(), geolocation=()ブラウザ API の制限
X-XSS-Protection1; mode=blockXSS フィルターの有効化

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 で管理しておけば設定内容も一目で分かる。

← Blog