34
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsの開発環境でhttpsを使う

Posted at

注意:puma前提

これをリファクタリングした
https://gist.github.com/tadast/9932075#gistcomment-2283895

この手法のメリットは、puma起動時にRubyスクリプトで証明書を発行するので、一度導入すれば開発者個人で証明書を作る必要がないこと

証明書置き場作成

$ mkdir config/certs && touch config/certs/.keep
.gitignore
/config/certs/*
!/config/certs/.keep

証明書作成・参照

config/puma.rb に以下を追加して、サーバー起動時に証明書を参照するようにする。
証明書がないなら勝手に作るようにする。

config/puma.rb
if Rails.env.development?
  key_file = Rails.root.join("config", "certs", "localhost.key")
  cert_file = Rails.root.join("config", "certs", "localhost.cert")

  unless key_file.exist?
    root_key = OpenSSL::PKey::RSA.new(2048)
    key_file.write(root_key)

    root_cert = OpenSSL::X509::Certificate.new.tap do |root_ca|
      root_ca.version = 2 # cf. RFC 5280 - to make it a "v3" certificate
      root_ca.serial = 0x0
      root_ca.subject = OpenSSL::X509::Name.parse "/C=BE/O=A1/OU=A/CN=localhost"
      root_ca.issuer = root_ca.subject # root CA"s are "self-signed"
      root_ca.public_key = root_key.public_key
      root_ca.not_before = Time.now
      root_ca.not_after = root_ca.not_before + 2 * 365 * 24 * 60 * 60 # 2 years validity
      root_ca.sign(root_key, OpenSSL::Digest::SHA256.new)
    end
    cert_file.write(root_cert)
  end

  ssl_bind "0.0.0.0", "8443", {
    key: key_file.to_path,
    cert: cert_file.to_path
  }
end

(Chromeのみ)localhostでSSLの警告を出ないようにする

やらなくてもいいですが、やっておくと便利

Chromeで以下にアクセス
chrome://flags/#allow-insecure-localhost

Allow invalid certificates for resources loaded from localhost. をEnabledにする。
image.png

rails server

いつも通りrails serverでサーバーを起動して、https://localhost:8443/ にアクセスする。
何も間違えていなければ、これでhttpsで繋がるはず。

34
30
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
34
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?