将Laravel项目部署到AWS后非基础路由出现404错误求助
Laravel部署AWS后非基础路由404解决方案
这是因为Laravel需要把所有请求都转发到public/index.php处理,但AWS服务器默认没配置对应的URL重写规则,所以除了根路由,其他路由都没法被框架解析,返回了服务器原生的404错误。
不同环境的解决办法
1. Apache服务器(EC2或传统主机)
- 先启用Apache的
mod_rewrite模块:sudo a2enmod rewrite sudo systemctl restart apache2 - 修改Apache站点配置文件(比如
/etc/apache2/sites-available/your-site.conf),在站点的<Directory>块里设置AllowOverride All,指向Laravel的public目录:<Directory /var/www/html/你的Laravel项目路径/public> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> - 确认Laravel的
public目录下存在.htaccess文件,内容如下(没有的话直接创建):<IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> RewriteEngine On # 处理授权头 RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # 移除末尾斜杠 RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # 所有请求转发到index.php RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule> - 重启Apache生效:
sudo systemctl restart apache2
2. Nginx服务器(EC2或Elastic Beanstalk)
- 修改Nginx配置文件(EC2里一般是
/etc/nginx/sites-available/your-site.conf,Elastic Beanstalk则在项目根目录创建.platform/nginx/conf.d/laravel.conf),添加重写规则:location / { try_files $uri $uri/ /index.php?$query_string; } - 确保配置里的
root指向Laravel的public目录:root /var/www/html/你的Laravel项目路径/public; - 测试配置并重启Nginx:
sudo nginx -t sudo systemctl restart nginx
3. AWS Elastic Beanstalk(PHP环境)
- 在项目根目录创建
.platform/nginx/conf.d/laravel.conf文件,写入上面Nginx的重写规则即可,重新部署应用后平台会自动加载这个配置。
额外检查项
- 给Laravel目录设置正确权限,让web服务器用户(比如
www-data)能读写storage和bootstrap/cache:sudo chown -R www-data:www-data /var/www/html/你的Laravel项目路径 sudo chmod -R 755 /var/www/html/你的Laravel项目路径/storage sudo chmod -R 755 /var/www/html/你的Laravel项目路径/bootstrap/cache - 如果之前生成过路由缓存,清除一下:
php artisan route:clear
内容的提问来源于stack exchange,提问作者Moomen S. Aldahdouh
相关产品推荐
相关产品推荐

