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

CodeIgniter 4中如何移除、修改Cache-Control响应头并解决设置后重复追加问题

Hey there! Let's sort out that duplicate Cache-Control header issue you're facing in CodeIgniter 4.

The problem happens because your current code is adding two separate Cache-Control entries: first via setCache() (which adds max-age=60), then via setHeader() (which appends public instead of replacing the existing header). Here are two clean ways to fix this:

CodeIgniter 4's setCache() method supports directly including cache directives like public in its options array. This way, it generates a single, properly formatted Cache-Control header automatically:

$response = service('response');
$cacheOptions = [
    'public' => true,       // Mark the response as publicly cacheable
    'max-age' => 60,        // Cache for 60 seconds
    // Add other directives here if needed, e.g., 'no-cache' => true
];
$response->setCache($cacheOptions);

This will set a single Cache-Control: public, max-age=60 header, no duplicates included.

Option 2: Manually replace the Cache-Control header

If you need full control over the exact header value, first remove any existing Cache-Control headers, then set your custom one:

$response = service('response');
// Remove all existing Cache-Control headers
$response->removeHeader('Cache-Control');
// Set your custom Cache-Control value
$response->setHeader('Cache-Control', 'public, max-age=60');

Alternatively, you can use the third parameter of setHeader() to force replacement instead of appending:

$response = service('response');
$response->setCache(['max-age' => 60]);
// Pass true as the third argument to replace the existing header
$response->setHeader('Cache-Control', 'public, max-age=60', true);

Either approach will eliminate the duplicate header issue by ensuring only one Cache-Control entry is sent with your response.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 07:02:39