19

我认为这应该相当容易,但我不熟悉它是如何完成的......

您如何编写一个 before 过滤器来检查当前请求是否针对某些子域,如果是,则将其重定向到相同的 url 但在不同的子域上?

即:blog.myapp.com/posts/1很好,但blog.myapp.com/products/123重定向到www.myapp.com/products/123.

我在想类似...

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

你怎么写那个重定向?

4

4 回答 4

15

ActionController::Redirecting#redirect_to允许你传递一个绝对 URL,所以最简单的方法是传递一个类似的东西:

redirect_to request.url.sub('blog', 'www')
于 2012-05-15T04:50:59.033 回答
7

从子域重定向到子域的简单选择如下

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

这将在域名上调用,例如 foo.apple.com 然后会转到 www.apple.com

于 2014-10-19T02:55:05.823 回答
1

无需执行字符串 sub 或指定控制器或操作的更简单的选项是使用

redirect_to url_for(subdomain: 'www', only_path: false)
于 2020-03-31T15:52:36.867 回答
1

一个简单的解决方案是

redirect_to dummy_rul(subdomain: 'subdomain')

例子:

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

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

“edv”是我的子域

于 2021-01-05T14:00:07.743 回答