Linux服务器CodeIgniter3项目如何访问/var目录外的/data文件?
解决CodeIgniter3访问服务器/data目录文件的404问题
问题根源
Web服务(Apache/Nginx)默认仅允许访问网站根目录(/var/www/html)内的资源,直接通过URL访问/data这类根外目录会被拦截,触发404错误。
可行解决方案
1. 创建符号链接(推荐)
在网站根目录下创建指向目标目录的软链接,让Web服务能通过网站根路径访问到/data里的文件:
ln -s /data/admin_assets /var/www/html/admin_assets
之后需要调整文件访问路径:
- 要么修改数据库中的路径为相对网站根的路径:
/admin_assets/upload_files/Photos/nala/start_photo.jpg - 要么在CodeIgniter视图中用
base_url()拼接路径:echo base_url('admin_assets/upload_files/Photos/nala/start_photo.jpg');
2. 配置Web服务允许访问/data目录
Apache配置
编辑Apache站点配置文件(比如/etc/apache2/sites-available/000-default.conf),添加别名规则:
Alias /admin_assets /data/admin_assets <Directory /data/admin_assets> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory>
重启Apache生效:
systemctl restart apache2
之后即可通过/admin_assets/upload_files/...的URL访问文件,可选择修改数据库路径或在代码中转换路径。
Nginx配置
编辑Nginx站点配置文件(比如/etc/nginx/sites-available/default),在server块内添加:
location /admin_assets { alias /data/admin_assets; autoindex off; }
重启Nginx生效:
systemctl restart nginx
同样用/admin_assets/...的路径访问文件即可。
3. 通过CodeIgniter控制器代理访问
如果不想改动Web服务配置或创建软链接,可以写一个控制器来读取文件并返回:
- 创建
application/controllers/FileController.php:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class FileController extends CI_Controller { public function get_file($path) { $full_path = '/data/admin_assets/upload_files/' . $path; if (!file_exists($full_path)) { show_404(); } $mime = mime_content_type($full_path); $this->output->set_content_type($mime); $this->output->set_output(file_get_contents($full_path)); } }
- 在
application/config/routes.php中添加路由规则:
$route['file/(:any)'] = 'FileController/get_file/$1';
- 访问时使用URL:
http://你的域名/file/Photos/nala/start_photo.jpg,数据库中只需存储Photos/nala/start_photo.jpg部分,在视图中拼接成该URL即可。
内容的提问来源于stack exchange,提问作者Shubham Nayak
相关产品推荐
相关产品推荐

