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

CodeIgniter3中外部CSS文件无法加载的问题求助

CodeIgniter3 外部CSS加载404问题解决

问题详情

尝试加载外部CSS时返回404错误:

http://localhost/Codeigniter_Project/css/style.css net::ERR_ABORTED 404 (Not Found)

相关代码:

视图文件(registration.php)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css" media="all">
    <title>Workctrl Assignment</title>
</head>

控制器文件(Regis.php)

<?php
class Regis extends CI_Controller
{
    public function index()
    {
        $this->load->helper('url');
        $this->load->view('registration');
    }
}
?>

项目结构:
Folder Structure

已自动加载URL助手,问题仍存在。

解决步骤

  1. 核对CSS文件位置
    确保css文件夹位于项目根目录(Codeigniter_Project文件夹下),而非application目录内——CodeIgniter默认禁止直接访问application下的文件,会导致404。

  2. 修正base_url配置
    打开application/config/config.php,确认base_url设置正确,末尾必须带斜杠:

    $config['base_url'] = 'http://localhost/Codeigniter_Project/';
    

    缺少斜杠会导致生成的URL拼接错误,变成http://localhost/Codeigniter_Projectcss/style.css。

  3. 调整CSS引用路径
    可以改用site_url()生成路径(与base_url效果一致,但会自动处理index.php):

    <link rel="stylesheet" type="text/css" href="<?php echo site_url('css/style.css'); ?>" media="all">
    
  4. 检查URL重写规则(若使用.htaccess)
    如果配置了.htaccess移除index.php,确保规则不会拦截静态文件:

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
    

    上述规则会跳过实际存在的文件/目录,保证CSS等静态资源能被直接访问。

  5. 验证文件权限
    确保css文件夹权限为755,style.css文件权限为644,服务器拥有读取权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 15:50:29