Rails: redirect to current path but different subdomain
Asked Answered
F

5

20

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?

Fidele answered 15/5, 2012 at 4:29 Comment(0)
J
16

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')
Joyajoyan answered 15/5, 2012 at 4:50 Comment(1)
Doh! The sub method is just the plain old ruby sub method... ok so after further experimentation this works but I have to use more of a regex to take care of it. The request.url object gives me enough to figure out the rest though, thanks!Fidele
C
7

A simple choice to redirect from subdomain to subdomain would be the following

redirect_to subdomain: 'www', :controller => 'www', :action => "index"

This would be called on a domain name for example foo.apple.com would then go to www.apple.com

Correll answered 19/10, 2014 at 2:55 Comment(0)
B
2

An even simpler option without the need to do a string sub or specify the controller or action would be to use

redirect_to url_for(subdomain: 'www', only_path: false)
Buster answered 31/3, 2020 at 15:52 Comment(0)
T
1

A simple solution for this is

redirect_to dummy_rul(subdomain: 'subdomain')

Example:

redirect_to projects_url(subdomain: 'edv') it will redirect on below url

"http://edv.maindomain.com/projects"

"edv" is my subdomain

Thibodeaux answered 5/1, 2021 at 14:0 Comment(0)
T
0

With more recent versions of Rails you may need the allow_other_host: true option in redirect() to prevent an error from being thrown.

Tareyn answered 29/10, 2023 at 13:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.