# 在反向代理后通过HTTPS提供服务时，会话cookie未标记为Secure

- **ID:** `security/session-cookie-secure-flag-missing-behind-proxy`
- **领域:** security
- **类别:** config_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

应用服务器只看到来自反向代理的HTTP（TLS在代理处终止），因此不会在会话cookie上设置Secure属性，导致cookie在纯HTTP下暴露于窃听风险。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Nginx 1.25 | active | — | — |
| Apache 2.4 | active | — | — |
| HAProxy 2.8 | active | — | — |

## 解决方案

1. ```
   配置反向代理转发X-Forwarded-Proto头。对于Nginx：proxy_set_header X-Forwarded-Proto $scheme; 并在应用中信任代理，当此头为'https'时设置安全cookie。
   ```
2. ```
   在应用程序配置文件中设置'Secure'属性，例如在Django中：SESSION_COOKIE_SECURE = True，但仅在生产环境中。
   ```
3. ```
   使用代理级重写向Set-Cookie头添加Secure属性。对于Nginx，使用headers-more-nginx-module：more_set_headers 'Set-Cookie: $upstream_http_set_cookie; Secure'
   ```

## 无效尝试

- **** — Forcing HTTPS on the application server directly without configuring the proxy headers may cause redirect loops or break the proxy connection. (50% 失败率)
- **** — Removing the proxy and using direct TLS termination on the app server is often not feasible in existing infrastructure. (40% 失败率)
- **** — Simply setting the Secure flag unconditionally in code may break local development over HTTP. (30% 失败率)
