Gitlab迁移至新Debian服务器后出现422 CSRF令牌验证失败错误
GitLab迁移后登录报错422及SSL问题排查与解决
问题背景
按照GitLab官方备份恢复指南将实例迁移至另一台Debian服务器,两台服务器的nginx.conf、gitlab.rb、GitLab虚拟主机等配置完全一致,备份恢复过程输出显示成功:
- 使用独立Nginx(而非GitLab内置Nginx),虚拟主机配置符合官方文档要求
- 采用Let's Encrypt SSL证书,
mydomain.com与gitlab.mydomain.com共用同一证书
遇到的问题
- 访问
gitlab.mydomain.com会重定向到登录页面,但提交登录请求后返回错误:
422
The change you requested was rejected.
Firefox在错误页面提示SSL证书问题:
Connection not secure: Parts of this page are not secure (such as images)查看
/var/log/gitlab/gitlab-rails/production_json.log日志,发现核心报错:
"exception.class": "ActionController::InvalidAuthenticityToken", "exception.message": "Can't verify CSRF token authenticity."
当前gitlab.rb配置
external_url 'https://gitlab.mydomain.com' pages_external_url 'https://pages.mydomain.com' # Disable the built-in nginx nginx['enable'] = false # Disable the built-in puma puma['enable'] = false # Set the internal API URL gitlab_rails['internal_api_url'] = 'https://gitlab.mydomain.com'' #disable status nginx['status'] = { 'enable' => false } # Define the web server process user (ubuntu/nginx) web_server['external_users'] = ['www-data']
排查与解决步骤
1. 修复CSRF令牌验证失败(422错误)
- 修正gitlab.rb配置错误:注意到
gitlab_rails['internal_api_url']末尾多了一个单引号,修正为:gitlab_rails['internal_api_url'] = 'https://gitlab.mydomain.com' - 重新配置并重启GitLab:
gitlab-ctl reconfigure gitlab-ctl restart - 验证Nginx反向代理请求头:确保Nginx虚拟主机配置包含以下头信息,保证CSRF令牌正确传递:
proxy_set_header Host $http_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; proxy_set_header X-Forwarded-Ssl on;
2. 解决混合内容SSL错误
- 检查资源协议引用:通过浏览器开发者工具(F12)的「网络」标签,确认GitLab所有内部资源(图片、CSS、JS)均使用HTTPS协议,无HTTP请求。
- 强制HTTP转HTTPS:在Nginx虚拟主机配置中添加重定向规则,确保所有HTTP请求跳转至HTTPS:
重启Nginx生效:server { listen 80; server_name gitlab.mydomain.com; return 301 https://$server_name$request_uri; }systemctl restart nginx - 清除浏览器缓存:Firefox的混合内容提示可能来自缓存的旧资源,清除缓存后重新访问。
3. 额外验证
- 修复文件权限:运行以下命令自动修复GitLab相关目录权限:
gitlab-ctl reconfigure - 检查服务状态:确认所有GitLab服务正常运行:
gitlab-ctl status
内容的提问来源于stack exchange,提问作者enzo
相关产品推荐
相关产品推荐

