LoginSignup
93
96

More than 5 years have passed since last update.

Railsのローカル環境にhttps(SSL)を導入する方法

Last updated at Posted at 2012-12-26

環境は、rails 3.2.6、ruby 1.9.3、Google Chrome 22.0、Mac 10.7.5 です。


一行目のruby.exerubyと変更しscript/sslrailsを追加します。
(デフォルトでscript/railsというファイルがありますが、それとは別に追加します)
※余談ですが、私はエディタをEsppressoを利用していまして、Esppresso上でscript/railsを複製をしたら、Unix実行ファイルとして複製されませんでした。なので、Finderで複製することができました。sslrailsは「Unix実行ファイル」でないと動作しませんので、ご注意下さい。

script/sslrails
#!/usr/bin/env ruby
# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.

APP_PATH = File.expand_path('../../config/application',  __FILE__)
require File.expand_path('../../config/boot',  __FILE__)

require 'rubygems'
require 'rails/commands/server'
require 'rack'
require 'webrick'
require 'webrick/https'
require 'webrick/ssl'

module Rails
  class Server < ::Rack::Server
    def default_options

      # cn と comment を適当に設定
      cn = [[ "CN", WEBrick::Utils::getservername]]  
      comment = "Generated by Ruby/OpenSSL"   
      cert, rsa = WEBrick::Utils::create_self_signed_cert(1024, cn, comment)
      ssl_certificate = cert.to_s
      ssl_private_key = rsa.to_s

      super.merge({
          :Port => 443,
          :environment => (ENV['RAILS_ENV'] || "development").dup,
          :daemonize => false,
          :debugger => false,
          :pid => File.expand_path("tmp/pids/server.pid"),
          :config => File.expand_path("config.ru"),
          :SSLEnable => true,
          :SSLVerifyClient => OpenSSL::SSL::VERIFY_NONE,
          :SSLPrivateKey => OpenSSL::PKey::RSA.new(ssl_private_key),
          :SSLCertificate => OpenSSL::X509::Certificate.new(ssl_certificate),
          :SSLCertName => cn
      })
    end
  end
end

require 'rails/commands'

次に、config/environments/development.rbに、config.force_ssl = trueを追加します。
※この状態は、httpでhttpのポートとともにアクセスしようとしても、強制的にすべてhttpsになります。

最後に、ローカルサーバーを起動します。
script/sslrails server webrick
すると、このサイトのセキュリティ証明書は信頼できませんと真っ赤でドキッとした画面が登場しますが、気にせず続行して下さい。

https:でサイトが表示されていれば、完了です。


via http://d.hatena.ne.jp/ikad/20110610/1307693546
大変参考にさせていただきました。ありがとうございます。


2014/3/29 追記

Rails 4.0.2でも同様に行けましたので、追記しておきます。

  1. binディレクトリの中に、rails_httpsというファイルを作ります。
  2. 上記のscript/sslrailsの内容をrails_httpsに書き込みます
  3. bin/rails_https sで起動します
  4. https://localhostにアクセスします。

こんなエラーが出たら

bash
bin/rails_https: Permission denied

以下のコマンドで権限を変更しましょう。

bash
chmod 755 bin/rails_https

こんなエラーが出たら2

bash
/Users/user_name/.rbenv/versions/2.1.0-rc1/lib/ruby/2.1.0/socket.rb:206:in `bind': Permission denied - bind(2) for 0.0.0.0:443 (Errno::EACCES)

なにやらポートが芳しくないので、rails_httpsを修正しましょう。

bash
      super.merge({
          :Port => 8282, # ここを8000番以上に変更

以上です。

93
96
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
93
96