Nginx的跨域Content Security Policy通行设置

  • 发表于
  • 日志

场景描述

A站点HTTPS,A站点做为中心站,引用B/C/D/E/F……站点的资源进行供给,确定的只有A站点是HTTPS,其它站点可能是HTTP也可能是HTTPS,文件类型不限定,包括但不限于:CSS,JS,IMAGE,MP4,MP3,RAR,ZIP,M3U8,FLV……。

如果你使用的是默认配置,那么它会提示以下错误:

知道通常情况下,HTTPS引用HTTP的资源就会出现跨域错误,但今天我们的要求是允许它跨域,并且尽量保证它是基本安全的。

在上周我测试过很多方案,最终使用的是:

意思是将所有HTTP请求尽可能的转换成HTTPS请求,如果对方同时支持HTTPS和HTTP协议,那这没有任何问题,但如果对方只支持HTTP,那这时候就会报错:

看到提示后直觉告诉我要去放行img-src和media-src,但当我去放行设置后,问题依旧,甚至还多出了错误。

Content-Security-Policy内容安全策略

内容安全策略(CSP)需要仔细调整和精确定义策略。如果启用,CSP会对浏览器呈现页面的方式产生重大影响(例如,默认情况下禁用内联JavaScript,并且必须在策略中明确允许)。CSP可防止各种攻击,包括跨站点脚本和其他跨站点注入。

Values

DirectiveDescription
base-uriDefine the base uri for relative uri.
default-srcDefine loading policy for all resources type in case of a resource type dedicated directive is not defined (fallback).
script-srcDefine which scripts the protected resource can execute.
object-srcDefine from where the protected resource can load plugins.
style-srcDefine which styles (CSS) the user applies to the protected resource.
img-srcDefine from where the protected resource can load images.
media-srcDefine from where the protected resource can load video and audio.
frame-srcDeprecated and replaced by child-src. Define from where the protected resource can embed frames.
child-srcDefine from where the protected resource can embed frames.
frame-ancestorsDefine from where the protected resource can be embedded in frames.
font-srcDefine from where the protected resource can load fonts.
connect-srcDefine which URIs the protected resource can load using script interfaces.
manifest-srcDefine from where the protected resource can load manifest.
form-actionDefine which URIs can be used as the action of HTML form elements.
sandboxSpecifies an HTML sandbox policy that the user agent applies to the protected resource.
script-nonceDefine script execution by requiring the presence of the specified nonce on script elements.
plugin-typesDefine the set of plugins that can be invoked by the protected resource by limiting the types of resources that can be embedded.
reflected-xssInstructs a user agent to activate or deactivate any heuristics used to filter or block reflected cross-site scripting attacks, equivalent to the effects of the non-standard X-XSS-Protection header.
block-all-mixed-contentPrevent user agent from loading mixed content.
upgrade-insecure-requestsInstructs user agent to download insecure resources using HTTPS.
referrerDefine information user agent must send in Referer header.
report-uriSpecifies a URI to which the user agent sends reports about policy violation.
report-toSpecifies a group (defined in Report-To header) to which the user agent sends reports about policy violation.

Example

Content-Security-Policy: script-src 'self'

在经过反复测试后

解决了全部问题,即消除全部警告,同时兼容了各种协议资源。

参考