php怎么部署线上vue前后端分离_跨域带cookie要配啥【说明】

2次阅读

vue前端部署后请求php接口出现403/401或cookie不携带,根本原因是cors策略与cookie属性未协同配置:需前端axios设withcredentials:true、后端精确设置access-control-allow-origin(非*)、access-control-allow-credentials:true,并将session.cookie_samesite设为none且启用secure、httponly、domain等属性,nginx还需正确代理并透传cookie头。

php怎么部署线上vue前后端分离_跨域带cookie要配啥【说明】

Vue 前端部署后请求 PHP 接口 403/401 或 Cookie 不携带?先看 Access-Control-Allow-Origin

跨域带 Cookie 的核心限制不在 PHP 本身,而在浏览器的 CORS 策略:只要前端发请求时加了 credentials: 'include'(Vue Axios 默认不加,需显式配置),后端就必须返回 Access-Control-Allow-Origin 的具体域名(不能是 *),同时必须带上 Access-Control-Allow-Credentials: true

PHP 后端常见错误写法:
header('Access-Control-Allow-Origin: *'); → 直接被浏览器拦截,Cookie 不会发送,且后续响应被丢弃。

正确做法(在 PHP 入口或中间件中):

if (isset($_SERVER['HTTP_ORIGIN'])) {     $origin = $_SERVER['HTTP_ORIGIN'];     // 白名单校验,避免任意域名伪造     $allowed_origins = ['https://your-vue-domain.com', 'https://www.your-vue-domain.com'];     if (in_array($origin, $allowed_origins)) {         header("Access-Control-Allow-Origin: $origin");         header('Access-Control-Allow-Credentials: true');         header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');         header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');         header('Access-Control-Expose-Headers: X-Auth-Token, X-Request-ID');     } } // 处理预检 OPTIONS 请求 if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {     exit(0); }

Vue Axios 发送带 Cookie 请求必须显式配置 credentials

Vue 项目里用 axiosfetch 默认都不会携带 Cookie,即使域名同源(前后端分离后通常不同域),必须主动声明。

立即学习PHP免费学习笔记(深入)”;

  • axios:每个请求加 { withCredentials: true },或全局设置:
    axios.defaults.withCredentials = true
  • fetch:必须加 credentials: 'include',例如:
    fetch('/api/login', { method: 'POST', credentials: 'include', body: json.stringify(data) })
  • Vue router 或 Pinia 持久化登录态时,注意首次页面加载后才发起请求 —— 如果服务端依赖 Cookie 鉴权,而前端没带,就会 401

PHP Session 跨域失效?检查 session.cookie_samesite 和 cookie 域名

即使 CORS 和 Axios 都配对了,PHP 的 session_start() 仍可能拿不到旧会话,原因常出在 Cookie 属性上:

  • session.cookie_samesite 默认是 Lax(PHP 7.3+),跨站 POST 请求会被浏览器阻止发送 Cookie;线上需设为 None,但强制要求 Secure(即只走 HTTPS)
  • 解决方法(在 PHP 启动前或入口文件顶部):
    ini_set('session.cookie_samesite', 'None');<br>ini_set('session.cookie_secure', '1');<br>ini_set('session.cookie_httponly', '1');<br>ini_set('session.cookie_domain', '.your-domain.com'); // 注意开头的点,支持子域
  • 如果用 Nginx 反向代理 Vue 静态资源,别漏掉 proxy_cookie_domain 重写 Cookie 域名,否则浏览器可能因 domain 不匹配拒绝存储

Nginx 配置补漏:静态资源和 API 路由不能混为一谈

很多线上部署把 Vue dist/ 目录扔进 PHP 项目根目录,靠 try_files 回退到 index.html,但这样容易让 /api/xxx 请求也被 PHP 路由捕获,绕过 CORS 头输出。

推荐结构:Nginx 分开代理

location / {     root /var/www/vue-dist;     try_files $uri $uri/ /index.html; } <p>location ^~ /api/ { proxy_pass <a href="https://www.php.cn/link/e911087c91c63c9d3e7ee83e372d10f7">https://www.php.cn/link/e911087c91c63c9d3e7ee83e372d10f7</a>; # 指向 PHP-FPM 或 Swoole 服务 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme;</p><h1>关键:透传 Cookie,且允许客户端带凭证</h1><pre class='brush:php;toolbar:false;'>proxy_pass_request_headers on; proxy_cookie_path / "/; Secure; HttpOnly; SameSite=None";

}

注意 proxy_cookie_path 这行不是万能解,实际生效依赖后端是否已正确 setcookie;它只是兜底补全属性,真正源头还得在 PHP 里控制 setcookie()$options 参数。

最易忽略的一点:开发时用 localhost:8080 + localhost:8000 测试没问题,但上线后域名、HTTPS、SameSite、CORS 头、Nginx 代理链 —— 五者必须全部对齐,缺一不可。任何一个环节漏掉 Secure 标志或 Origin 白名单,Cookie 就静默消失。

text=ZqhQzanResources