Help us understand the problem. What is going on with this article?

railsで旧ドメインから新ドメインに引っ越す

More than 3 years have passed since last update.

.htaccess使ったりdnsで変更したりするのかな…ちゃんとパスとかも引き継いでくれる書き方あるのかな…あんまり詳しくないから調べるのめんどくせぇな…、と思ったんですがrailsでやれるんですね。

application.rb
class ApplicationController
  before_filter :ensure_domain
  #...
  protected
  def ensure_domain
    default_host = Rails.application.routes.default_url_options[:host]
    if request.env['HTTP_HOST'] != default_host && Rails.env.production?
     redirect_to "#{request.protocol}#{default_host}#{request.fullpath}", status: 301
    end
  end
end

config/environments/production.rb
Rails.application.configure do

  Rails.application.routes.default_url_options[:host] = 'example.com'

#...

end

この手のproduction環境でのみ有効になる条件ってテスト書いてても不安になるのでリリース前にはstagingとかで目で見て挙動を確認するんですが、安心できるいい方法が知りたい所です。

spec/controller/application_controller_spec.rb
  describe "production javascripts" do
    before(:each) do
      allow(Rails.env).to receive(:production?).and_return(true)
      @request.env['HTTP_HOST'] = 'old-domain.com'
      Rails.application.routes.default_url_options[:host] = 'example.com'
    end
    it "redirects user to new host if accessed old host" do
      get :index
      expect(response.status).to eq 301
      expect(response.header["Location"]).to include 'example.com'
    end
    end

そもそもこれだとダメだよー、とかもっと良い書き方あるよー、とかあったら教えて下さい!

参考
ruby on rails - Redirect from old domain to new one (SEO friendly) - Stack Overflow
Goodbye .htaccess, Hello Rails

foloinfo
foloinfo / CEO at byus&co.ltd // Vimmer, 最近はめっきりReact
https://drip.ink
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away