You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

生产HTTPS Apache服务器上Laravel应用X-CSRF Token与Session未生成问题

Laravel HTTPS环境下POST请求CSRF/Session Cookie丢失修复方案

1. 修正Laravel核心配置

  • 修改项目根目录下的.env文件,添加/更新以下配置:
    APP_URL=https://你的域名.com
    SESSION_SECURE_COOKIE=true
    CSRF_COOKIE_SECURE=true
    
  • 打开config/session.php,确认secure和same_site配置:
    'secure' => env('SESSION_SECURE_COOKIE', false),
    'same_site' => env('SESSION_SAME_SITE', 'lax'),
    
    注:same_site设为lax适配大多数生产场景,若存在跨域需求可改为none(需配合secure=true)。

2. 配置Apache服务器规则

  • 确保项目根目录的.htaccess包含HTTPS强制跳转和头信息传递规则:
    <IfModule mod_rewrite.c>
        <IfModule mod_negotiation.c>
            Options -MultiViews -Indexes
        </IfModule>
    
        RewriteEngine On
    
        # 强制所有请求跳转至HTTPS
        RewriteCond %{HTTPS} !=on
        RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
        # 传递X-Forwarded-Proto头,确保Laravel识别HTTPS环境
        RewriteCond %{HTTP:X-Forwarded-Proto} !https
        RewriteCond %{HTTPS} off
        RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
        # 处理Laravel路由重写
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ index.php [L]
    </IfModule>
    
  • 确认Apache已启用mod_rewrite和mod_headers模块,若未启用可执行以下命令(以Ubuntu为例):
    sudo a2enmod rewrite headers
    sudo systemctl restart apache2
    

3. 清理缓存与浏览器数据

  • 执行Laravel缓存清理命令,确保配置生效:
    php artisan config:clear
    php artisan cache:clear
    php artisan route:clear
    
  • 清除浏览器的缓存和Cookie,避免旧的非安全Cookie干扰。

4. 验证CSRF Token传递

  • 查看页面源码,确认@csrf指令已生成正确的隐藏输入框:
    <input type="hidden" name="_token" value="生成的CSRF令牌值">
    
  • 检查表单的action属性是否为HTTPS开头的正确地址,避免混合内容问题。

内容的提问来源于stack exchange,提问作者Bqdor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 19:08:26