Laravel切换APP_ENV至production后API路由无法访问求助
Laravel生产环境API路由无法访问排查方案
可能原因及调整项
1. 确认路由文件位置
- 检查你的
/test路由是否定义在routes/api.php中,而非routes/web.php。API路由默认自动携带/api前缀,若放在web.php,访问路径会不匹配。 - 执行命令查看所有注册路由,验证URI和请求方法:
php artisan route:list
2. 清除并重建路由缓存
生产环境Laravel会缓存路由,修改后需更新缓存:
php artisan route:clear # 可选:重新生成路由缓存 php artisan route:cache
3. 检查服务器配置
Apache环境
- 确保项目根目录指向
public文件夹,而非项目根目录。 - 确认
public/.htaccess文件存在且配置正确:<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> RewriteEngine On # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Send Requests To Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule> - 启用Apache的
mod_rewrite模块。
Nginx环境
- 配置文件需正确指向
public目录,并设置try_files规则:server { listen 80; server_name myweb.com; root /path/to/project-folder/public; add_header X-Frame-Options "SAMEORIGIN"; add_header X-Content-Type-Options "nosniff"; index index.php; charset utf-8; location / { try_files $uri $uri/ /index.php?$query_string; } location = /favicon.ico { access_log off; log_not_found off; } location = /robots.txt { access_log off; log_not_found off; } error_page 404 /index.php; location ~ \.php$ { fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; # 适配你的PHP版本 fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name; include fastcgi_params; } location ~ /\.(?!well-known).* { deny all; } } - 修改配置后重启Nginx:
sudo systemctl restart nginx
4. 修复目录权限
确保storage和bootstrap/cache目录拥有Web服务器用户(如www-data)的读写权限:
chown -R www-data:www-data storage bootstrap/cache chmod -R 775 storage bootstrap/cache
5. 查看错误日志
因APP_DEBUG=false,页面不显示详细错误,需查看Laravel日志文件storage/logs/laravel.log,根据日志定位具体问题。
6. 确认APP_URL配置
检查.env文件中的APP_URL是否匹配实际访问路径:
- 若使用子目录部署:
APP_URL=http://myweb.com/project-folder/public - 若配置虚拟主机指向
public:APP_URL=http://myweb.com
内容的提问来源于stack exchange,提问作者Muhammad Faisal
相关产品推荐
相关产品推荐

