Joe Walsh
Joe Walsh

Reputation: 210

Rails redirect_to loses the https protocol and goes to http

When using redirect_to example_path in the controller the protocol gets changed to http. I want the protocol to remain the same as the original request e.g. if I'm using https I want to be redirected to https://example_path... and if I'm using http I want to be redirected to http://example_path...

I know I can use config.force_ssl = true but I want ssl to be optional.

Upvotes: 7

Views: 2676

Answers (3)

Jong Bor Lee
Jong Bor Lee

Reputation: 3855

What worked for me was adding a line in my nginx config. I use nginx+unicorn, listening to http in port 3000 and https in port 3001.

Complete configuration file follows, place this in sites-available and replace [...] with something suitable:

upstream myapp {
    server unix:/tmp/unicorn.sock fail_timeout=0;
}

server {
    listen 3000;
    listen 3001 ssl;
    server_name example.com;

    ssl_certificate [...];
    ssl_certificate_key [...];

    root [...];

    try_files $uri/index.html $uri @myapp;

    location @myapp {
        proxy_pass http://myapp;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme; # I added this line
        proxy_redirect off;
    }

    error_page 500 502 503 504 /500.html;
    client_max_body_size 4G;
    keepalive_timeout 10;
}

Upvotes: 2

Corvin
Corvin

Reputation: 96

@ruby_newbie's answer didn't work for me. redirect_to with String ignored the protocol arg. Also I am using SSL termination with a proxy, so Rail's protocol may not be the same at what user is using. You could use only_path, but I ended up using protocol: '//' as follows:

redirect_to controller: 'example', action: 'show', protocol: '//'

Upvotes: 2

ruby_newbie
ruby_newbie

Reputation: 3285

redirect_to takes a protocol key in its args hash. You can do

redirect_to example_path, protocol: request.protocol

and that should get you sorted. Let me know if that doesn't work.

Upvotes: 2

Related Questions