Laravel虚拟主机配置核心是root/DocumentRoot必须指向public目录且所有请求经index.php处理:Apache需启用mod_rewrite、AllowOverride All和Require all granted;Nginx需配置try_files与fastcgi_param SCRIPT_FILENAME $realpath_root,并确保storage和bootstrap/cache权限正确。

部署 Laravel 项目时,虚拟主机配置不是“配完就能用”,而是决定路由是否生效、静态资源能否加载、环境是否安全的关键环节。核心就两点:Web 根目录必须是 public/,所有动态请求必须经由 index.php 统一入口处理。Apache 和 Nginx 实现方式不同,但目标一致。
Apache:靠 .htaccess + DocumentRoot + AllowOverride
Apache 默认不读取重写规则,必须主动启用并授权:
- 确保
mod_rewrite已启用:运行a2enmod rewrite,再重启 Apache -
DocumentRoot必须指向项目public/目录,例如:DocumentRoot /var/www/myapp/public - 在对应
<directory></directory>块中明确允许覆盖:AllowOverride All和Require all granted缺一不可 - 确认
public/.htaccess文件存在且内容规范,标准开头应为:RewriteEngine OnRewriteBase /(若部署在子目录如/myapp/,此处必须改为RewriteBase /myapp/)
后续规则需以RewriteRule ^(.*)$ index.php [L]或类似方式兜底
Nginx:靠 try_files + location + fastcgi_pass 显式定义
Nginx 不解析 .htaccess,所有逻辑必须写进 server 配置:
-
root指令直接设为public/路径,例如:root /var/www/myapp/public; - 主 location 块使用
try_files $uri $uri/ /index.php?$query_string;,优先服务真实文件,否则交由 index.php - PHP 处理块必须完整配置:
location ~ \.php$内含fastcgi_pass(指向 php-fpm socket 或端口)、include fastcgi_params,并确保SCRIPT_FILENAME使用$realpath_root而非$document_root,避免符号链接路径错误 - 子目录部署(如
http://site.com/myapp/)不能只改 root,要加专用 location:location ^~ /myapp/ {alias /var/www/myapp/public/;(注意末尾斜杠)try_files $uri $uri/ @myapp;}location @myapp {rewrite ^/myapp/(.*)$ /myapp/index.php?/$1 last;}
共性要点:权限、路径与调试
配置再准,权限或路径错一步,页面就白屏或 500:
- Web 服务器用户(如
www-data或nginx)必须对storage/和bootstrap/cache/有读写权限:sudo chown -R www-data:www-data storage bootstrap/cachesudo chmod -R 775 storage bootstrap/cache - 不要把整个 Laravel 项目放
/var/www/html下——这会让.env、config/等敏感目录暴露在公网 - 验证配置语法:
Apache:运行sudo apache2ctl configtest
Nginx:运行sudo nginx -t - 修改后务必 reload 服务,不是 restart:
sudo systemctl reload apache2或sudo systemctl reload nginx
配置本身不复杂,但每个环节都环环相扣。漏掉 AllowOverride All,.htaccess 就失效;少写一个斜杠,alias 就映射错位;SCRIPT_FILENAME 用错变量,就会提示“File not found”。稳住根目录、走通重写、守住权限,Laravel 就能跑起来。


















