LoginSignup
5
3

More than 5 years have passed since last update.

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

Posted at

.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

5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3