Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
3
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

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

.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

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
3
Help us understand the problem. What are the problem?