温馨提示×

ubuntu下thinkphp如何开启路由

小樊
44
2026-10-01 15:30:21
栏目: 编程语言

在 Ubuntu 下使用 ThinkPHP(以 ThinkPHP 5 / 6 为主,最常见)开启路由,一般包括 开启路由配置、编写路由规则、配置 Web 服务器(Nginx/Apache) 三个步骤。


一、开启 ThinkPHP 路由(框架层面)

1️⃣ 确认路由功能已开启

ThinkPHP 5

编辑配置文件:

vim application/config.php

确保以下配置:

'url_route_on' => true,
'url_route_must' => false, // true 表示必须走路由

ThinkPHP 6

编辑:

vim config/route.php

确认:

'url_route_on' => true,

2️⃣ 配置路由规则

ThinkPHP 5

路由文件:

application/route.php

示例:

use think\Route;

Route::get('hello/:name', 'index/Index/hello');

ThinkPHP 6

路由文件:

route/app.php

示例:

use think\facade\Route;

Route::get('hello/:name', 'Index/hello');

二、Ubuntu Web 服务器配置(关键)

✅ Nginx(最常见)

编辑 Nginx 配置:

sudo vim /etc/nginx/sites-available/default

关键配置(开启 PATH_INFO / 重写):

location / {
    if (!-e $request_filename) {
        rewrite ^(.*)$ /index.php?s=/$1 last;
    }
}

或 ThinkPHP 官方推荐:

location / {
    try_files $uri $uri/ /index.php$is_args$args;
}

重启 Nginx:

sudo systemctl restart nginx

✅ Apache

确保开启 mod_rewrite:

sudo a2enmod rewrite
sudo systemctl restart apache2

在项目根目录 .htaccess:

<IfModule mod_rewrite.c>
  Options +FollowSymlinks -Multiviews
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>

三、测试路由是否生效

访问:

http://your-domain.com/hello/thinkphp

如果正常返回,说明路由已开启 ✅


四、常见问题排查

404 错误

  • Nginx 未配置重写
  • 路由规则写错
  • 未重启 Web 服务

路由不生效

  • url_route_on = false
  • 使用了默认路由但未关闭
  • 缓存问题(清除 runtime)
rm -rf runtime/*

如果你能告诉我:

  • ThinkPHP 版本(5.0 / 5.1 / 6.0)
  • Web 服务器(Nginx / Apache)
  • 是否使用宝塔 / Docker

我可以给你完全对应的配置示例。

0 踩