Laravel 10.10+Vite部署AWS EC2后资源文件NotFound问题求助
解决方案
1. 检查Vite配置的基础路径
打开项目根目录的vite.config.js,确认base配置匹配你的部署路径:
- 若站点部署在域名根目录,确保
base为'/'或直接省略(默认值):
import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; export default defineConfig({ plugins: [ laravel({ input: [ 'resources/css/app.css', 'resources/js/app.js', ], refresh: true, }), ], // base: '/', // 默认根目录,可省略 });
- 若部署在子目录(如
https://xxx.com/laravel-app),则设置base: '/laravel-app/'。
2. 验证.env的APP_URL配置
确保.env中的APP_URL与EC2实例的访问地址完全一致:
APP_URL=http://你的EC2公网IP # 绑定域名则写APP_URL=https://你的域名
修改后刷新配置缓存:
php artisan config:cache
3. 检查Web服务器的静态资源路由配置
若使用Nginx:
在站点配置文件中,确认/build/assets目录的静态资源能被正确访问,同时避免被Laravel路由拦截:
# 单独配置build目录的静态资源规则 location ~* ^/build/assets/ { root /你的Laravel项目路径/public; expires 1y; add_header Cache-Control "public, immutable"; } # 主路由规则,优先访问静态文件 location / { try_files $uri $uri/ /index.php?$query_string; }
修改后重启Nginx:
sudo systemctl restart nginx
若使用Apache:
确认项目根目录的.htaccess包含以下规则(Laravel默认已有,可检查是否被修改):
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^ index.php [L]
这条规则会优先返回存在的静态文件,不会走Laravel路由。修改后重启Apache:
sudo systemctl restart httpd
4. 修复文件权限和所有者
EC2上的public/build目录权限可能导致Web服务器无法读取,执行以下命令:
# 设置所有者为Web服务器用户(Nginx用www-data,Apache根据镜像用apache或www-data) sudo chown -R www-data:www-data /你的Laravel项目路径/public/build # 设置正确权限 sudo chmod -R 755 /你的Laravel项目路径/public/build
5. 重新构建并清理缓存
先删除旧构建文件,再重新构建资源:
rm -rf public/build npm run build
同时清理Laravel视图缓存:
php artisan view:clear
6. 强制刷新浏览器缓存
浏览器可能缓存了旧的资源路径,按Ctrl+Shift+R(Windows/Linux)或Cmd+Shift+R(Mac)强制刷新页面,验证资源是否加载正常。
内容的提问来源于stack exchange,提问作者Manuel Luna Soto
相关产品推荐
相关产品推荐

