简体   繁体   English

Ruby on Rails 2.3.8:有没有办法始终转发到URL的https版本?

[英]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. 有时,主体的URL指向我的应用服务器上的图像。 Many of these URLs are HTTP. 这些URL中有许多是HTTP。

Is there anyway to redirect all HTTP requests to HTTPS? 无论如何,是否会将所有HTTP请求重定向到HTTPS?

I'm using Rails 2.3.8 我正在使用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. 由于某些浏览器安全设置将在查看HTTPS页面时阻止HTTP资产,因此您不希望在Web服务器级别(例如mod_rewrite)执行此操作,因为某些浏览器无法做到这一点。

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. 您不想在视图或控制器级别处理此问题-模型是您在其中执行业务规则(例如将其全部保留为HTTPS)的地方。

1) Prevent HTTP links from being saved 1)防止保存HTTP链接

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 2)清理现有内容

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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