简体   繁体   中英

Ruby on Rails 2.3.8: is there a way to always forward to the https version of an url?

So, in some of my database records, there is an object, "content" that has a body, much like a document would. Sometimes the body has URL that point to images on my app server. Many of these URLs are HTTP.

Is there anyway to redirect all HTTP requests to HTTPS?

I'm using Rails 2.3.8
and the Paperclip gem

Because some browser security settings will block HTTP assets when viewing a HTTPS page, you don't want to do this at the web server (eg mod_rewrite) level since some browsers won't make it that far.

You don't want to handle this at the view or controller level - the model is where you enforce business rules like keep it all HTTPS.

1) Prevent HTTP links from being saved

class Content < ActiveRecord::Base
  ...
  before_validation :force_https
  def force_https
    unless body.nil?
      self.body.gsub! /http:\/\/my\.app\.server/, 'https://my.app.server'
    end
  end
  ...
end

2) Clean up existing content

Fire up console and run this:

Content.all.each do |c|
  c.update_attribute 'body', 
     c.body.gsub(/http:\/\/my\.app\.server/, 'https://my.app.server')
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM