CodeIgniter本身不内置全局HTTPS强制跳转功能,需结合服务器配置(推荐首选,如Nginx用return 301或Apache用.htaccess重写)或框架层过滤器(如HttpsRedirect类)实现;同时须配置app.forceGlobalSecureRequests=true及baseURL为HTTPS,确保全站安全。

CodeIgniter 本身不内置全局 HTTPS 强制跳转功能,需结合服务器配置或框架层逻辑实现。推荐优先用服务器级重定向(更高效、更安全),其次再考虑在 CodeIgniter 中补充控制逻辑。下面分场景说明关键做法。
服务器配置(推荐首选)
这是最可靠、性能最好、对 SEO 友好的方式,所有请求在到达 PHP 之前就完成跳转。
-
Apache 环境:在网站根目录的
.htaccess文件中添加:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]确保 Apache 已启用 mod_rewrite,且虚拟主机允许 AllowOverride All。
-
Nginx 环境:在监听 80 端口的
server块中加入:
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}同时确保 443 端口的 server 块已正确配置 SSL 证书路径和 TLS 参数。
CodeIgniter 应用层补充(适合开发/测试环境或特殊需求)
若无法修改服务器配置(如共享主机),可在 CodeIgniter 入口或基础控制器中加判断。注意:仅作兜底,不能替代服务器级跳转。
- 在
app/Config/Filters.php中注册一个全局过滤器:
public $globals = [
'before' => [
'https_redirect'
],
];- 创建过滤器类
app/Filters/HttpsRedirect.php:
namespace App\Filters;
<p>use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;</p><p>class HttpsRedirect implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
if (! $request->isSecure()) {
$uri = $request->getUri();
$redirectUrl = 'https://' . $uri->getHost() . $uri->getURI();
return redirect()->to($redirectUrl, 'location', 301);
}
}</p><pre class="brush:php;toolbar:false;">public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
}}
该方式能适配反向代理(如 Nginx + PHP-FPM),自动识别 X-Forwarded-Proto 等头信息,比直接读 $_SERVER['HTTPS'] 更健壮。
框架配置与安全加固
跳转只是第一步,还需配合以下设置确保全站真正走 HTTPS:
- 在
.env文件中开启强制协议:
app.baseURL = "https://www.php.cn/link/ff2c61cc989878560095849ad3cefe02" app.forceGlobalSecureRequests = true
- 启用
forceGlobalSecureRequests后,CodeIgniter 会自动为生成的 URL(如site_url()、base_url())使用 HTTPS,并对 Cookie 设置Secure标志; - 检查
app/Config/App.php中的$cookieSecure和$cookieHttpOnly是否设为true; - 避免在视图中硬编码
http://链接,统一用base_url()或site_url()生成资源路径。
本地开发环境适配
本地开发通常无 HTTPS,但又要避免代码出错:
- 在
.env中按环境区分 baseURL:
# .env
CI_ENVIRONMENT = development
app.baseURL = "https://www.php.cn/link/d6686469a29701048799005b5ebb1529"
<h1>或使用条件判断(如在 App.php 中)</h1><p>if (ENVIRONMENT === 'production') {
$config['baseURL'] = '<a href="https://www.php.cn/link/ff2c61cc989878560095849ad3cefe02">https://www.php.cn/link/ff2c61cc989878560095849ad3cefe02</a>';
} else {
$config['baseURL'] = '<a href="https://www.php.cn/link/d6686469a29701048799005b5ebb1529">https://www.php.cn/link/d6686469a29701048799005b5ebb1529</a>';
}- 如需本地也跑 HTTPS,可用 mkcert 工具快速生成可信本地证书,再配置 Nginx/Apache 或 PHP 内置服务器支持。


















