Search code examples
ruby-on-railssslnginxruby-on-rails-5

Rails 5 ActionController::InvalidAuthenticityToken on Production Enviroment Nginx


On Rails 5.2, SSL enviroment, running as reverse_proxy with Nginx, whenever I submit a form I get the error:

HTTP Origin header (https://agro2business.com.br) didn't match request.base_url (https://agro2business.com.br, agro2business.com.br)

Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken)

I'd read about configuring params and Nginx for passing on headers in another StackOverflow questions but no luck so far. My nginx config file:

proxy_pass http://localhost:4000; }

location / {

            proxy_pass http://localhost:4000;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-Port $server_port;
            proxy_set_header X-Real-Scheme $scheme;
            proxy_set_header X-NginX-Proxy true;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-Ssl on;
    }

Why is Rails trying to compare the header with two values?

request.base_url (https://agro2business.com.br, agro2business.com.br)


Solution

  • My problem was that in my nginx config I was setting header Host two times and this was causing url generation misleadings, which in turn was invalidating form submissions.

      proxy_pass http://localhost:4000;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            **proxy_set_header Host $http_host;**
            proxy_redirect off;
            proxy_set_header X-Real-IP  $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            **proxy_set_header Host $http_host;**
            proxy_set_header X-Real-Port $server_port;
            proxy_set_header X-Real-Scheme $scheme;
            proxy_set_header X-NginX-Proxy true;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-Ssl on;
    

    Just removing one the two proxy_set_header Host $http_host; did the trick