【问题标题】:Dynamic routing rails动态布线导轨
【发布时间】:2014-07-25 02:02:46
【问题描述】:

我想将所有到 http://domain.com/blog/category/post 的请求重定向到一个外部博客 URL 说。 http://blog.domain.com/category/post.

我最终做了类似的事情。

match "/blog" => redirect("http://blog.domain.com/"), :via => [:get] 
match "/blog/:section" => redirect("http://blog.domain.com/%{section}"), :via => [:get] 
match "/blog/:section/:subsection" => redirect("http://blog.domain.com/%{section}/%{subsection}"), :via => [:get]
match "/blog/:section/:subsection/:post" => redirect("http://blog.domain.com/%{section}/%{subsection}/%{post}"), :via => [:get]

有没有更通用的解决方案?如何将所有请求重定向到以“/blog”为前缀的 URL 以路由到特定控制器,或重定向到带有某些参数的 url?

【问题讨论】:

标签: ruby-on-rails ruby routes


【解决方案1】:

经过一番研究,我通过这样做实现了它。

    match "/blog(*path)" => redirect(Proc.new { |params, request|
        request_uri = request.instance_variable_get(:@env)['REQUEST_URI']
        split_urls = request_uri.sub(/\/blog/,"|").split("|")
        "http://domain.blog.com/" + split_urls.last
    }), :via => [:get]

【讨论】:

    【解决方案2】:

    如果您真的需要在 Rails 中执行此操作,您可以使用通配符映射到控制器方法的路由,如下所示:

    match '/blog/*path', to: 'foo#redirect'
    

    然后在控制器中:

    class FooController
      def redirect
        redirect_to "http://blog.domain.com/#{path}"
      end
    end
    

    但正如 Damien 上面所说,最好在 Nginx/Apache 级别执行此操作。

    【讨论】:

    • 这可行,但参数不会被传递。 (例如)/blog/first?utm_campaign=facebook 需要转到 blog.domain.com/first?utm_campaign
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多