---
title: Cookie 前缀 __Host- 与 __Secure-:约束与最佳实践
keywords:
- __Host-
- __Secure-
- Set-Cookie
- Secure
- Path
- Domain
description: 说明 __Host-/__Secure- 前缀的语义与约束、示例与部署建议,提升 Cookie 的安全性与隔离性,避免跨站与子域滥用。
categories:
- 文章资讯
- 编程技术
---
概述
Cookie 前缀通过语义约束提升安全性:__Secure- 要求 Secure,允许设置 Domain/Path;__Host- 要求 Secure 且 Path=/,不可设置 Domain(仅作用于当前主机)。
示例
# __Secure-:必须 Secure,可以设置 Domain/Path
Set-Cookie: __Secure-session=abc; Secure; Path=/; SameSite=Lax
# __Host-:必须 Secure,Path=/,且不可设置 Domain
Set-Cookie: __Host-session=xyz; Secure; Path=/; SameSite=Lax
工程建议
- 登录态与关键状态:优先使用
__Host-前缀以限制作用域于当前主机;其他安全 Cookie 使用__Secure-。 - 组合策略:同时设置
SameSite与最小权限的Path;启用 HTTPS 与 HSTS。 - 监控与审计:定期审查第三方与子域写入行为;记录异常与风险。
参考与验证
- MDN Cookie 前缀说明:https://developer.mozilla.org/docs/Web/HTTP/Cookies#cookie_prefixes
- IETF RFC 6265bis 草案:https://httpwg.org/http-extensions/draft-ietf-httpbis-rfc6265bis.html
- web.dev Cookie 安全指南:https://web.dev/articles/cookies#secure_prefixes

发表评论 取消回复