# Gitea Custom Template 内联脚本被 CSP Nonce 拦截


## 现象

把 Matomo 统计脚本放进 `$GITEA_CUSTOM/templates/custom/header.tmpl`（渲染在 `</head>` 之前）后，页面里始终没有统计数据。浏览器控制台报：

```
Executing inline script violates the following Content Security Policy directive 'script-src * 'nonce-<random>''. Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. The action has been blocked.
```

## 原因

Gitea 1.27.0 把 CSP 的内联脚本策略改成了 per-request nonce（[PR #37232](https://github.com/go-gitea/gitea/pull/37232)）：每个响应生成一个随机 nonce，`script-src` 变成 `* 'nonce-xxx'`，外部脚本照常放行，但内联 `<script>` 只有带上这个 nonce 才会执行。custom template 里的内联脚本没有 nonce 属性，直接被浏览器拦掉。1.27.0 的[发布说明](https://blog.gitea.com/release-of-1.27.0/)也提示了这点：custom templates 里注入的内联 `<script>` 需要更新后才能继续执行。

## 解决

给 script 标签加上 nonce 属性，值用模板变量 `{{ctx.CspScriptNonce}}`：

```html
<script nonce="{{ctx.CspScriptNonce}}">
  // 你的内联脚本，例如 Matomo 统计代码
</script>
```

保存后重启 Gitea（容器部署直接重启容器），刷新页面，控制台不再报 CSP 拦截错误，统计面板里能看到访客。


---

> 作者: Nite  
> URL: https://www.nite07.com/zh-cn/posts/gitea-csp-nonce-inline-script/  

