Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rails Local Development over HTTPS

Refactor of https://gist.github.com/tadast/9932075#gistcomment-2283895

$ mkdir config/certs && touch config/certs/.keep
# .gitignore

/config/certs/*
!/config/certs/.keep
# 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

For Chrome

  1. Access to chrome://flags/#allow-insecure-localhost
  2. Enable Allow invalid certificates for resources loaded from localhost.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment