Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: redirect to current path but different subdomain

I think this should be fairly easy but I'm not familiar with how it's done...

How do you write a before filter that would check if the current request is for certain subdomains, and if so redirect it to the same url but on a different subdomain?

Ie: blog.myapp.com/posts/1 is fine but blog.myapp.com/products/123 redirects to www.myapp.com/products/123.

I was thinking something like...

class ApplicationController < ActionController::Base
  before_filter :ensure_domain

  protected
  def ensure_domain
    if request.subdomain == 'blog' && controller_name != 'posts'
      redirect_to # the same url but at the 'www' subdomain...
    end
  end
end

How do you write that redirect?

like image 909
Andrew Avatar asked May 15 '12 04:05

Andrew


Video Answer


1 Answers

ActionController::Redirecting#redirect_to allows you to pass an absolute URL, so the easiest thing to do would be to pass it one with something like:

redirect_to request.url.sub('blog', 'www')
like image 81
Todd A. Jacobs Avatar answered Oct 11 '22 13:10

Todd A. Jacobs