Romain-p
Romain-p

Reputation: 475

Redirect domain to www.domain with Rails

Hello, Im new with Ruby on Rails and I would like to add some properties to redirect automatly my domain.com to www.domain.com

I've looked at existed closed issues but everythings work with .htaccess, but I dont have it with Rails.

EDIT:

Saw this link : Redirect non-www requests to www urls in Rails But seems not updated, I got this error using the code in answer (request_uri not found)

EDIT II

From http://apidock.com/rails/ActionDispatch/Http/URL/request_uri I saw we have to use now request.url

Tried it and got wrong URL using the following code:

class ApplicationController < ActionController::Base
  before_filter :add_www_subdomain

  private
  def add_www_subdomain
    unless /^www/.match(request.host)
      redirect_to("#{request.protocol}x.com#{request.url}",
                  :status => 301)
    end
  end
end

My domain becomes also strange

Upvotes: 1

Views: 422

Answers (1)

Romain-p
Romain-p

Reputation: 475

I found myself, the following code is gonna add www. to your url if there are not into.

class ApplicationController < ActionController::Base
  before_filter :add_www_subdomain

  private
  def add_www_subdomain
    unless /^www/.match(request.host)
      redirect_to("#{request.url}".gsub("#{request.protocol}", "#{request.protocol}www."), status: 301)
    end
  end
end

Upvotes: 1

Related Questions