最根本有效的做法是将public目录外的代码全部置于web根目录不可达位置,确保.env、app/、config/等敏感文件无法通过url访问;nginx root必须指向实际存放index.php的路径(如/www/wwwroot/example.com),并配置try_files与$realpath_root,再通过location规则禁止访问敏感文件扩展名。

部署 Laravel 11 到 Nginx 时,把 public 目录之外的代码全部置于 Web 根目录不可达位置,是防止源码泄露最根本、最有效的做法。这不是“加固选项”,而是 Laravel 安全模型的强制前提——所有敏感文件(.env、app/、config/、bootstrap/、vendor/、database/ 等)必须无法通过任何 URL 访问。
将 public 内容移入 web 根,核心代码上移一级
这是生产环境推荐的标准结构,尤其适合共享主机或宝塔等面板环境:
- 设 Web 服务器根目录为
/www/wwwroot/example.com(即public_html类路径) - 把原 Laravel 项目中
public/下的所有内容(index.php、css/、js/、images/等)直接复制进去 - 把剩余所有目录和文件(
app/、bootstrap/、config/、database/、.env、composer.json等)放到/www/wwwroot/example.com的上级目录,例如:/www/wwwroot/laravel-app/ - 修改
public/index.php中的两处路径引用(复制过去后已变成/www/wwwroot/example.com/index.php):
→ 将require __DIR__.'/../vendor/autoload.php';改为require '/www/wwwroot/laravel-app/vendor/autoload.php';
→ 将$app = require_once __DIR__.'/../bootstrap/app.php';改为$app = require_once '/www/wwwroot/laravel-app/bootstrap/app.php';
Nginx 配置必须严格指向 public 内容所在路径
即使你已物理分离代码,Nginx 的 root 指令仍需明确指向存放 index.php 的目录(即实际的 public 内容所在路径),不能指向项目根:
- ✅ 正确:
root /www/wwwroot/example.com;(该目录下有index.php) - ❌ 错误:
root /www/wwwroot/laravel-app;或root /www/wwwroot/laravel-app/public;(后者虽在项目内,但违背“public 外部署”初衷,且易因路径嵌套出错) - 确保
location /块含标准转发:try_files $uri $uri/ /index.php?$query_string; - PHP 处理块中使用
$realpath_root防止符号链接问题:fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
额外封堵常见泄露入口
物理隔离 + 正确 root 是基础,再加几道防线可杜绝意外:
- 在 Nginx
server块中显式禁止访问敏感文件:location ~ /\.(env|git|htaccess|htpasswd|log|ini|lock|yml|yaml|xml|md)$ { deny all; } - 关闭目录列表:
autoindex off;(避免用户访问空路径看到Index of /) - 隐藏 Nginx 版本:
server_tokens off; - 确认
.env文件权限为644或更严(如600),且所属用户与 Nginx 进程一致(如www-data),确保即使配置失误也不会被读取
验证是否真正安全
部署完成后,手动测试几个关键路径:
- 访问
https://yoursite.com/.env→ 应返回 403 或 404,绝不能下载或显示内容 - 访问
https://yoursite.com/config/database.php→ 同样应拒绝访问 - 访问
https://yoursite.com/robots.txt或/css/app.css→ 应正常返回 - 访问任意路由如
/login或/api/user→ 应由 Laravel 正常响应,而非 404











