在 Ubuntu 下使用 ThinkPHP(以 ThinkPHP 5 / 6 为主,最常见)开启路由,一般包括 开启路由配置、编写路由规则、配置 Web 服务器(Nginx/Apache) 三个步骤。
编辑配置文件:
vim application/config.php
确保以下配置:
'url_route_on' => true,
'url_route_must' => false, // true 表示必须走路由
编辑:
vim config/route.php
确认:
'url_route_on' => true,
路由文件:
application/route.php
示例:
use think\Route;
Route::get('hello/:name', 'index/Index/hello');
路由文件:
route/app.php
示例:
use think\facade\Route;
Route::get('hello/:name', 'Index/hello');
编辑 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
确保开启 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
如果正常返回,说明路由已开启 ✅
url_route_on = falserm -rf runtime/*
如果你能告诉我:
我可以给你完全对应的配置示例。