配置PHP框架虚拟主机需正确设置Web服务器并启用URL重写。1. Apache需启用mod_rewrite模块,配置VirtualHost指向public目录,AllowOverride All以支持.htaccess重写规则;2. Nginx在server块中设置root为public目录,通过try_files实现请求重写至index.php,并配置fastcgi_pass连接PHP-FPM;3. 各框架如Laravel、ThinkPHP、Symfony均需确保入口文件在public下,配合正确重写规则即可运行。

配置PHP框架的虚拟主机环境,关键在于正确设置Web服务器(Nginx或Apache),让请求能正确指向框架的入口文件(如index.php),并支持URL重写。下面分别介绍在 Nginx 和 Apache 中如何为常见的PHP框架(如 Laravel、ThinkPHP、Symfony 等)配置虚拟主机。
Apache 配置虚拟主机
Apache 是 PHP 开发中最常用的 Web 服务器之一,配置简单,适合本地开发和小型项目。
1. 启用必要的模块
确保以下模块已启用:
立即学习“PHP免费学习笔记(深入)”;
- mod_rewrite:用于 URL 重写
- mod_vhost_alias(可选):支持动态虚拟主机
在 Ubuntu/Debian 上可通过命令启用:
a2enmod rewrite a2ensite your-site.conf systemctl restart apache2
2. 配置虚拟主机文件
编辑 Apache 的站点配置文件(通常位于 /etc/apache2/sites-available/your-project.conf):
ServerName yourapp.test DocumentRoot /var/www/your-project/public AllowOverride All Require all granted Options -MultiViews +FollowSymLinks ErrorLog ${APACHE_LOG_DIR}/your-project_error.log CustomLog ${APACHE_LOG_DIR}/your-project_access.log combined
说明:
ServerName:设置访问域名,需在本地 hosts 添加映射(如127.0.0.1 yourapp.test)DocumentRoot:指向框架的public目录(Laravel、Symfony 等)或public/www入口AllowOverride All:允许 .htaccess 文件生效,用于路由重写3. 框架自带的 .htaccess(如 Laravel)
确保
public/.htaccess存在且内容正确,将所有请求重写到 index.php:RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [QSA,L]Nginx 配置虚拟主机
Nginx 性能更高,适合生产环境,配置方式与 Apache 不同,不依赖 .htaccess。
1. 创建站点配置文件
在
/etc/nginx/sites-available/your-project中添加配置:server { listen 80; server_name yourapp.test; root /var/www/your-project/public; index index.php index.html;location / { try_files $uri $uri/ /index.php?$query_string; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; # 根据实际版本调整 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } location ~ /\.ht { deny all; }}
说明:
root指向框架的 public 目录try_files实现路由重写,将请求转发给 index.php 处理fastcgi_pass需匹配 PHP-FPM 的监听地址- 静态文件和隐藏文件(如 .htaccess)被正确处理
2. 启用站点
ln -s /etc/nginx/sites-available/your-project /etc/nginx/sites-enabled/ nginx -t # 测试配置 systemctl reload nginx3. 本地 hosts 映射
编辑本地
/etc/hosts(Windows 在C:\Windows\System32\drivers\etc\hosts):127.0.0.1 yourapp.test常见框架注意事项
Laravel:必须将根目录设为
public/,.env 文件权限正确,开启重写。ThinkPHP:若使用 Apache,.htaccess 放在入口目录;Nginx 配置类似,注意 pathinfo 支持。
Symfony:public 目录下有
index.php或使用 flex 结构,Nginx 推荐使用index.php入口。基本上就这些。只要 Web 服务器指向正确的入口目录,并开启 URL 重写,大多数 PHP 框架都能正常运行。配置完成后,访问
http://yourapp.test即可看到应用首页。











