Rails: redirect to current path but different subdomain

元气小坏坏 提交于 2019-11-29 16:57:23

问题


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?


回答1:


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')



回答2:


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



来源:https://stackoverflow.com/questions/10594155/rails-redirect-to-current-path-but-different-subdomain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!