PAYATHON 2026

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 设为空字符串,并同步配置服务器重写规则。

备注:内容仅供参考。