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

Ruby on Rails SSL配置故障:重定向过多及CSRF令牌不匹配

解决Rails应用HTTPS重定向循环及Origin不匹配问题

问题根源

开启config.force_ssl = true时出现重定向循环,是因为Nginx将HTTPS请求以HTTP方式转发给Rails,Rails收到HTTP请求后触发force_ssl重定向到HTTPS,Nginx再次将该请求转成HTTP发给Rails,形成循环。注释force_ssl后出现Origin不匹配错误,是因为Rails认为请求是HTTP,但实际用户访问的是HTTPS,导致Origin头和request.base_url协议不一致。

解决方案

1. 修正Nginx配置

更新/etc/nginx/sites-available/example,开启HTTP转HTTPS重定向,并添加转发头告知Rails实际请求协议:

server {
    listen 80;
    server_name example.com www.example.com;
    # 开启HTTP到HTTPS永久重定向
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com www.example.com;
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        # 添加以下转发头,让Rails识别实际请求协议
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Port $server_port;
        proxy_cache_bypass $http_upgrade;
    }
}

2. 配置Rails信任代理转发头

修改config/environments/production.rb,开启force_ssl并信任本地Nginx代理:

# 强制所有请求使用HTTPS
config.force_ssl = true

# 信任本地127.0.0.1的代理请求(Nginx在同一服务器转发)
config.action_dispatch.trusted_proxies = IPAddr.new('127.0.0.1/32')

3. 重启服务生效

  • 重启Nginx:
    sudo systemctl restart nginx
    
  • 重启Rails应用(以Puma为例):
    sudo systemctl restart puma
    

验证

访问http://example.com,应自动跳转至https://example.com,网站正常加载,Rails日志中不再出现HTTP Origin header didn't match request.base_url错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 01:50:24