在 Debian 上排查与修复 Laravel 路由问题
一 快速自检清单
二 Web 服务器与 URL 重写配置
server {
listen 80;
server_name your_domain_or_ip;
root /var/www/your_project/public;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; # 按实际 PHP 版本调整
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
三 文件权限与目录可写
四 路由缓存与性能优化
[opcache]
zend_extension=opcache.so
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=4000
opcache.revalidate_freq=60
五 常见错误对照表
| 症状 | 可能原因 | 快速修复 |
|---|---|---|
| 访问 / 或 /api/xxx 返回 404 | Nginx 未配置 try_files;DocumentRoot 未指向 public;API 前缀遗漏 | 修正 Nginx/Apache 配置;确保访问 /api/xxx;执行 php artisan route:list 确认注册 |
| 路由更改不生效 | 启用了路由缓存 | 执行 php artisan route:clear(生产再 route:cache) |
| 白屏或 500 | storage、bootstrap/cache 不可写 | 设置目录属主为 www-data 并赋予 775/755 权限 |
| 返回 Method Not Allowed | 请求方法(GET/POST/PUT/DELETE)与路由定义不一致 | 调整路由或请求方法;用 php artisan route:list 核对 |
| 带参数路由 /user/{id} 匹配失败 | 参数缺失或顺序不一致 | 在 URL 或测试中补全参数;核对控制器方法签名 |
| 中间件拦截(如登录) | 未登录或中间件配置错误 | 登录后访问;检查中间件注册与应用范围 |
| 路由命名冲突 | 多个路由使用相同 name | 使用 ->name(‘唯一名’) 并确保唯一 |
| API 跨域问题 | 未正确配置 CORS | 安装并配置 fruitcake/laravel-cors,设置允许的来源与方法 |