You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何禁用Rails项目默认CSP,仅使用Content-Security-Policy-Report-Only?

解决Rails中secure-headers gem默认CSP头无法禁用的问题

你之前修改config/application.rb里的action_dispatch.default_headers无效,是因为这个默认的Content-Security-Policy头是由secure-headers gem自动生成的默认配置,而非Rails原生的默认响应头。

正确的处理方式是在secure-headers的初始化配置中直接禁用强制CSP头,只保留Report-Only模式的配置:

修改config/initializers/secure_headers.rb为以下内容:

SecureHeaders::Configuration.default do |config|
  # 禁用强制生效的Content-Security-Policy头
  config.csp = nil
  # 保留Report-Only模式的CSP配置
  config.csp_report_only = {
    default_src: %w['self' fonts.gstatic.com],
    img_src: %w['self'],
    font_src: %w['self' fonts.gstatic.com],
    script_src: %w['self'],
    connect_src: %w['self'],
    report_uri: %w[/my-route]
  }
end

额外检查项

确保项目中没有其他地方(比如控制器、自定义过滤器)手动设置Content-Security-Policy头,若有需一并移除,避免重复或冲突。

验证方法

重启Rails服务器后,打开浏览器开发者工具的「网络」面板,查看请求的响应头,确认仅存在Content-Security-Policy-Report-Only头,且无Content-Security-Policy头即可。

内容的提问来源于stack exchange,提问作者José Mateus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 05:42:09