Vue在phpEnv部署需据路由模式选择方案:一、hash模式直接放dist至www目录;二、history模式需配.htaccess重写;三、前后端分离用Nginx反向代理;四、同域跨子路径需PHP加CORS头。

如果您在phpEnv环境中部署Vue项目时遇到静态资源无法加载、路由404或接口跨域失败等问题,则可能是由于Web服务器未正确识别Vue构建产物或未适配History模式。以下是针对phpEnv环境的多种部署与配置方法:
一、将Vue构建产物直接放入phpEnv网站根目录
该方法适用于Vue使用默认hash路由模式,无需重写规则,部署最简捷。phpEnv默认网站根目录为 D:\phpenv\www(Windows)或 /opt/phpenv/www(Linux/macOS),所有静态文件必须置于该路径下可被直接访问。
1、在Vue项目根目录执行 npm run build 或 yarn build,生成 dist 文件夹。
2、打开 dist 文件夹,全选其中所有文件(含 index.html、js/、css/、assets/ 等子目录)。
立即学习“PHP免费学习笔记(深入)”;
3、将其粘贴至 phpEnv 的默认网站根目录,例如:D:\phpenv\www\my-vue-app\。
4、启动phpEnv的Apache与MySQL服务,在浏览器中访问 http://localhost/my-vue-app/,确认 index.html 正常加载且页面交互可用。
二、配置Apache支持Vue History路由模式
当Vue Router启用 history 模式时,直接访问 /user/profile 会触发Apache 404错误,因该路径实际不存在物理文件。需通过 .htaccess 启用URL重写,将所有非资源请求回退至 index.html 处理。
1、确保 phpEnv 中 Apache 已启用 mod_rewrite 模块(默认已开启)。
2、在 Vue 部署目录(如 D:\phpenv\www\my-vue-app\)下新建文件,命名为 .htaccess。
3、用文本编辑器打开 .htaccess,写入以下内容:
RewriteEngine On
RewriteBase /my-vue-app/
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /my-vue-app/index.html [L]
4、保存文件,重启 phpEnv 的 Apache 服务。
5、刷新浏览器访问 http://localhost/my-vue-app/user/profile,验证路由跳转不再报404。
三、通过phpEnv内置Nginx反向代理实现前后端分离
该方案将Vue前端静态资源与PHP后端API完全解耦:前端由Nginx直接托管,后端PHP服务运行于独立端口(如9001),Nginx负责将 /api/ 路径请求代理至后端,避免跨域问题。
1、将Vue构建产物放入独立目录,例如:D:\phpenv\nginx\html\frontend\。
2、修改 phpEnv Nginx 配置文件 D:\phpenv\nginx\conf\nginx.conf,在 http 块内添加 server 配置:
server {
listen 80;
server_name localhost;
root D:/phpenv/nginx/html/frontend;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location /api/ {
proxy_pass http://127.0.0.1:9001/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
3、启动PHP后端服务(如使用 php -S 127.0.0.1:9001 -t D:/phpenv/www/api/),确保接口可通过 http://127.0.0.1:9001/login 访问。
4、重启 phpEnv 的 Nginx 服务,访问 http://localhost/ 加载前端,并检查浏览器开发者工具 Network 标签页中 /api/ 请求是否返回200。
四、解决Vue调用PHP接口时的跨域问题(不使用代理)
若选择将Vue与PHP共置于同一域名但不同子路径(如前端 /,后端 /api/),需在PHP接口入口处统一注入CORS响应头,使浏览器允许前端脚本读取响应内容。
1、在PHP后端所有接口文件顶部(或统一中间件中)添加如下代码:
<?php
header('Access-Control-Allow-Origin: http://localhost');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
header('Access-Control-Allow-Credentials: true');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
exit(0);
}
// 后续业务逻辑...
2、确保Vue中 axios 请求 baseURL 设置为 '/api/'(相对路径),而非 'http://localhost:8000/api/'。
3、重启phpEnv的Apache服务,清除浏览器缓存后重新访问页面,检查控制台是否仍有 CORS 错误提示。











