Railsでのhttp/https切り換えはには実行環境に依存する部分もある

現在、開発しているWebアプリではプライバシーを扱う一部のページのみ httpsで実行し、それ以外の大部分のページは httpなので、httpからhttpsへの遷移や httpsからhttpへの遷移があります。

Ruby on Railsでは http から https へ遷移する リンクやは下のように

<% link_to :action => 'login', :controller => 'members', :only_path => false, :protocol => 'https' %>

また、https から http へ遷移は

<% link_to :action => 'logout', :controller => 'members', :only_path => false, :protocol => 'http' %>

と書きます。form_for でも同様です。

今時のRailsアプリは map.resoures を用いたRESTfulアプリになっているので members_login_url などのヘルパーメソッドを使ってURLを指定する場合が多いと思いますが、その場合は

<% link_to members_login_url(:protocol => 'https') %>

と書くと https ページに遷移できます。


さて今回、開発していてテスト環境では

<% link_to members_logout_url %>

と書くと https から http ページに遷移できたので、そのまま本番環境(まだ運用されてないのでステージング環境?)で動かしてみましたが、
なぜか上の書き方では https から http に切り替わりませんでした。


いろいろと試してみたところ、開発環境の mongrel + apache mod_porxy と 本番環境 apache + passnger の違いのようでした。

対処として、https から http へ遷移も protocol => 'http'を省略しないことです (無精するなです ^^;)

<% link_to members_logout_url(:protocol => 'http') %>


viewのいたるところに :only_path => false, :protocol => 'https' を書くのは DRY では無いので以下のようなヘルパーを書いて使っています。

helper
  def http_prot(opts = {})
    {:only_path => false, :protocol => 'http'}.merge(opts)
  end

  def https_prot(opts = {})
    {:only_path => false, :protocol => 'https'}.merge(opts)
  end
view
<% link_to members_login_url(https_proto) %>

<% link_to members_login_url(https_proto(:sw => 1)) %>

<% link_to https_proto(:action => 'login', :controller => 'members') %>