Nithin Krishna
Nithin Krishna

Reputation: 107

Dynamic routing rails

I want to redirect all requests to http://domain.com/blog/category/post to an external blog url say. http://blog.domain.com/category/post.

I ended up, doing something like.

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]

Is there a more genric solution to this? How can I redirect all requests to URLs prefixed with '/blog' to be routed to a particular controller, or to a url with some parameters?

Upvotes: 2

Views: 126

Answers (2)

Nithin Krishna
Nithin Krishna

Reputation: 107

After some research, I achieved it by doing something like this.

    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]

Upvotes: 1

Sam Starling
Sam Starling

Reputation: 5378

If you really needed to do it in Rails, you could have a route with a wildcard map to a controller method, like this:

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

And then in the controller:

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

But as Damien said above, it's better to do this at the Nginx/Apache level.

Upvotes: 0

Related Questions