CodeIgniter 3 在 PHP 内置服务器下 base_url() 为何丢失端口和 index.php
数据小陈
结论: 本地用 php -S localhost:8000 启动、又没有做 URL 重写时,不要依赖 $config['base_url'] = '' 的自动检测。把 base_url 显式设为 http://localhost:8000/,index_page 保持为 index.php,站内链接统一用 site_url() 生成。base_url() 只把基础 URL 和传入路径拼在一起,不会自动补上 index.php;自动检测也不保证能保留 :8000。
原因
base_url()和site_url()的职责不同。base_url('productos/crear')只是把base_url配置值和路径拼起来;site_url('productos/crear')使用的是base_url + index_page + 路径,默认index_page为index.php,所以才会得到http://localhost:8000/index.php/productos/crear。- CI3 在
base_url为空时会尝试用服务器变量推导地址,常见实现是基于SERVER_ADDR、SCRIPT_NAME等,并不能可靠地使用浏览器地址栏中的HTTP_HOST。在 PHP 内置服务器下,这会丢掉非默认端口8000,也可能得到127.0.0.1、::1等地址。浏览器访问http://localhost/productos/crear实际走 80 端口,因此连接会被拒绝。 - PHP 内置服务器不会读取
.htaccess。在未重写的情况下,URL 必须显式包含index.php,这也是base_url()不能替代site_url()的原因。
推荐做法
在 application/config/config.php 中为本地环境显式配置:
$config['base_url'] = 'http://localhost:8000/';
$config['index_page'] = 'index.php';
视图中统一使用 site_url():
<a href="<?= site_url('productos/crear') ?>">新建产品</a>
也可以使用 URL 辅助函数:
<?= anchor('productos/crear', '新建产品') ?>
这样生成的链接是:
http://localhost:8000/index.php/productos/crear
注意事项
- 如果继续使用
base_url(),需要自己写全index.php,例如base_url('index.php/productos/crear');但更推荐用site_url()。 - 不要为了让
base_url()带上index.php,而把base_url配成http://localhost:8000/index.php/,这会让base_url的语义变得混乱。 - 生产环境不要把本地
localhost:8000提交到公共配置;按环境覆盖配置或使用环境变量。 - 如果以后配置了 URL 重写并希望去掉
index.php,再把index_page设为空字符串,并同步配置服务器重写规则。
备注:内容仅供参考。
