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

RunCloud环境下Nginx缓存文件存在时跳过proxy_pass的实现方案

Nginx缓存优先配置(适配RunCloud环境)

问题背景

使用runcloud.io管理服务器时,Nginx配置支持注入自定义配置,但常规方式无法实现优先读取缓存文件、缓存不存在时再走代理的需求——因为RunCloud会自动在location /块末尾包含带有proxy_pass的配置文件,导致代理请求始终被触发,缓存从未生效。

无效配置示例

location / {
    # 此处可注入自定义配置,例如:
    try_files /page-cache/$uri @proxy;

    # RunCloud会自动在块末尾包含该文件,其中包含proxy_pass配置
    include /etc/nginx/conf/proxy.conf;
}

解决方案思路

通过if指令配合额外的location块实现:

  • 针对缓存文件目录单独配置location,内部使用try_files处理缓存读取
  • 在主location /中,通过if检查缓存文件是否存在;若存在则用rewrite ... last跳转到缓存对应的location,从而绕过RunCloud自动注入的代理配置

有效配置示例

location /page-cache/ {
    try_files $uri @proxy;
}

location / {
    set $cache_path "/page-cache"; # URI以/开头
    set $use_cache 0;
    set $cache_file "";

    # 检查是否存在目录形式的缓存文件(如/page-cache/xxx/index.html)
    if (-f "$document_root$cache_path$uri/index.html") {
        set $use_cache 1;
        set $cache_output "HIT";
        set $cache_file $cache_path$uri/index.html;
    }

    # 检查是否存在单文件形式的缓存文件(如/page-cache/xxx.html)
    if (-f "$document_root$cache_path$uri.html") {
        set $use_cache 1;
        set $cache_output "HIT";
        set $cache_file $cache_path$uri.html;
    }

    # 如果请求带有x-page-cache Cookie,则绕过缓存
    if ($http_cookie ~* "x-page-cache") {
        set $use_cache 0;
        set $cache_output "bypass cookie";
    }

    # 符合缓存条件时,跳转到缓存文件对应的location
    if ($use_cache = 1) {
        rewrite .* $cache_file last;
    }

    # RunCloud自动注入的代理配置
    include /etc/nginx/conf/proxy.conf;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:13:14