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

Sphinx中如何强制自定义JS/CSS文件不缓存、始终加载更新?

解决Sphinx自定义CSS/JS文件浏览器缓存问题

以下是几种实用的解决方法,按需选择:

1. 手动给文件名添加版本号

每次修改自定义CSS/JS后,直接在文件名里加上版本号或修改标识,比如把custom.css改成custom.v2.css、custom.js改成custom.v2.js,同步修改conf.py里的配置:

html_css_files = ['css/custom.v2.css']
html_js_files = ['js/custom.v2.js']

这种方法简单直接,浏览器会把带新版本号的文件识别为全新资源,自动重新加载。

2. 自动添加构建时间戳作为URL参数

通过修改Sphinx模板文件,给静态文件URL自动附加构建时间戳,避免手动修改文件名:

  • 在文档源目录下创建_templates文件夹(无则新建)
  • 复制Sphinx默认的layout.html模板到该文件夹(默认模板可从Sphinx安装目录或项目默认模板中获取)
  • 打开layout.html,找到引用CSS和JS的代码块,修改为:
{% for css_file in css_files %}
  <link rel="stylesheet" href="{{ pathto(css_file, 1) }}?v={{ build_date|strftime('%Y%m%d%H%M%S') }}" type="text/css" />
{% endfor %}

{% for js_file in js_files %}
  <script src="{{ pathto(js_file, 1) }}?v={{ build_date|strftime('%Y%m%d%H%M%S') }}"></script>
{% endfor %}

每次构建文档时,当前构建时间戳会作为URL参数,浏览器会因URL不同重新加载最新文件。

3. 通过服务器配置禁用缓存

如果文档通过Nginx、Apache等服务器部署,可直接在服务器配置中指定目标文件不被缓存:

Nginx配置示例

location ~* /_static/(css/custom\.css|js/custom\.js) {
    expires -1;
    add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
}

Apache配置示例

<FilesMatch "^custom\.(css|js)$">
    Header set Cache-Control "no-store, no-cache, must-revalidate, max-age=0"
    Header set Pragma "no-cache"
</FilesMatch>

服务器会在响应头中告知浏览器不要缓存这些文件,每次请求都会返回最新版本。

内容的提问来源于stack exchange,提问作者Danny Beckett

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:22:33