Amazon EC2 Beanstalk部署Laravel显示代码而非页面问题求助
解决Laravel + Elastic Beanstalk部署的典型问题
看来你刚上手Laravel+Beanstalk部署,踩了几个新手常见的坑,我来一步步帮你理清解决思路:
1. 为什么修改DocumentRoot后显示PHP源码?
这是因为Apache没有正确解析PHP文件,直接把index.php的内容当成纯文本输出了。Beanstalk默认的Apache配置可能缺少PHP处理规则,或者PHP模块未正确加载。
推荐解决方案(用Beanstalk配置文件持久化修改)
直接改EC2实例的httpd.conf容易被Beanstalk的环境更新覆盖,更稳妥的方式是在项目根目录创建.ebextensions/apache.config配置文件,让Beanstalk自动帮你配置:
files: "/etc/httpd/conf.d/laravel.conf": mode: "000644" owner: root group: root content: | <Directory /var/www/html/public> AllowOverride All Require all granted </Directory> # 确保Apache能解析PHP文件 AddHandler application/x-httpd-php .php <FilesMatch \.php$> SetHandler application/x-httpd-php </FilesMatch> container_commands: 01_update_document_root: command: | sed -i 's/ DocumentRoot \"\/var\/www\/html\"/ DocumentRoot \"\/var\/www\/html\/public\"/' /etc/httpd/conf/httpd.conf
2. 解决权限拒绝问题
Laravel的storage和bootstrap/cache目录需要写入权限,否则会触发权限错误。同样在刚才的.ebextensions/apache.config里添加权限修复命令:
# 接上面的container_commands 02_fix_laravel_permissions: command: | chown -R apache:apache /var/www/html/storage chown -R apache:apache /var/www/html/bootstrap/cache chmod -R 755 /var/www/html/storage chmod -R 755 /var/www/html/bootstrap/cache
3. 关于URL加/public的问题
修改DocumentRoot指向/var/www/html/public后,就不需要在URL里手动加/public了——这才是Laravel的正确部署方式,public目录本来就是Web根目录,能保护你的核心代码不被直接访问。
最后验证步骤
- 把
.ebextensions/apache.config放到项目根目录 - 重新打包代码并上传到Beanstalk
- 等待部署完成后访问你的域名,应该就能正常显示Laravel首页了
如果还是有问题,可以去Beanstalk控制台查看环境日志,或者登录EC2实例看Apache错误日志/var/log/httpd/error_log,里面会有具体的错误信息帮你排查。
内容的提问来源于stack exchange,提问作者Travis Cornelius
相关产品推荐
相关产品推荐

