Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何根据域名有条件地强制SSL?_Ruby On Rails_Ssl_Https_Ruby On Rails 4_Routes - Fatal编程技术网

Ruby on rails 如何根据域名有条件地强制SSL?

Ruby on rails 如何根据域名有条件地强制SSL?,ruby-on-rails,ssl,https,ruby-on-rails-4,routes,Ruby On Rails,Ssl,Https,Ruby On Rails 4,Routes,我的Rails应用程序有两个域名:app.example.com和short.net。较长的域是标准域,需要HTTPS,较短的域是提供短URL的方便域,需要HTTP 目前我正在强制SSL: config.force_ssl = true 但我真的只想对更长的域名强制使用SSL。如何根据域名有条件地强制SSL?短域名将重定向到主域名,然后强制使用SSL。这将避免短域名需要SSL证书 想法?向应用程序控制器添加一些配置: class ApplicationController < Actio

我的Rails应用程序有两个域名:app.example.com和short.net。较长的域是标准域,需要HTTPS,较短的域是提供短URL的方便域,需要HTTP

目前我正在强制SSL:

config.force_ssl = true
但我真的只想对更长的域名强制使用SSL。如何根据域名有条件地强制SSL?短域名将重定向到主域名,然后强制使用SSL。这将避免短域名需要SSL证书


想法?

应用程序控制器添加一些配置:

class ApplicationController < ActionController::Base
   force_ssl if: :ssl_required?

   [...]

   private
   def ssl_required?
     request.host == 'app.example.com'
   end
end
class ApplicationController
来源:

类应用程序控制器
在Rails 5及更高版本中,您可以也应该通过执行此操作,因为Rails 6.0的控制器中不推荐使用
强制ssl
,并且将在6.1中删除

config.force_ssl = true
config.ssl_options = {
  redirect: {
    exclude: ->(request) { request.host == 'app.example.com' }
  }
}

这真是个有趣的时机。我在下面发布了我的解决方案,与您的建议非常接近。我试图在routes.rb文件中解决这个问题,但我认为我更喜欢这种方法。请注意,在控制器中设置
force_ssl
,并没有实现与配置中的
config.force_ssl
相同的功能。除了强制重定向之外,基于配置的版本还将HST和安全cookie添加到每个响应()
语法错误,意外“:“强制ssl如果::需要ssl?”
config.force_ssl = true
config.ssl_options = {
  redirect: {
    exclude: ->(request) { request.host == 'app.example.com' }
  }
}