Change protocol to https in all rails helpers

后端 未结 9 1583
情书的邮戳
情书的邮戳 2020-12-10 12:55

Rails 3.1+ I want my url helpers to use the https protocol without having to specify it in every helper I call. After searching around I\'ve found various ways but none work

相关标签:
9条回答
  • 2020-12-10 13:17

    You can add this code to ApplicationController

      def default_url_options(options={})
        options.merge(protocol: :https)
      end
    

    You can also check out to Getting Rails URL helpers to automatically output https urls

    0 讨论(0)
  • 2020-12-10 13:20

    For a rails 5.2.0 RESTAPI App the following worked:

    In each environment file as necessary ie config/environments/test.rb

      Rails.application.routes.default_url_options[:protocol] = 'https'
    
    

    Controller code:

     Rails.application.routes.url_helpers.url_for(uploaded_file)
    
    0 讨论(0)
  • 2020-12-10 13:24

    If you want to force SSL on your application, this can be done by setting config.force_ssl to true in your application.rb (or your environment specific file). More on the subject here

    EDIT Ok so I don't find enough evidence for this, but I think you can override default_url_options=(options={}) in application controller, and set :protocol => :https in the function body. If this does not the trick for your emails, you'll have to repeat the procedure in your environment config by adding config.action_mailer.default_url_options. Hope this does it!

    0 讨论(0)
  • 2020-12-10 13:27

    Whichever environment you want to use ssl (https://), just add this config lines to its configuration file in config/environments:

    YOURAPPNAME::Application.configure do
    
      # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
      config.force_ssl = true
    end
    
    0 讨论(0)
  • 2020-12-10 13:31

    In Rails 3.2.1, by default force_ssl is true, let's check

    1. Open config/environments/production.rb and search "config.force_ssl"

    config.force_ssl = true - no need to change

    now in config/environments/development.rb - no need to place config.force_ssl, it should work, because your server running locally.

    Ok, here is the other view

    if !request.ssl?
      "https://" + request.host + request.request_uri
    elsif request.ssl?
      "http://" + request.host + request.request_uri
    end
    

    Add def in helper base on above if else and in the ActionView::Helpers, there is a url_for method that might get you what you want if you start using that.

    0 讨论(0)
  • 2020-12-10 13:34

    So you want it mainly for links in emails?

    I think this will work in your production.rb, development.rb or any other environment.

    config.action_mailer.default_url_options = {
      :host => 'yourwebsite.com',
      :protocol => 'https'
    }
    
    # Makes it possible to use image_tag in mails
    config.action_mailer.asset_host = "https://yourwebsite.com"
    
    0 讨论(0)
提交回复
热议问题