Philip7899
Philip7899

Reputation: 4677

Rails routes: redirect a wild card route

I have a website built in Ruby on Rails and a blog built in WordPress. The url for the main site will be example.com and the url for the blog is blog.example.com. Because of the way search engines index sites and the preference for a directory blog as opposed to a subdomain blog, I want to implement a permanent redirect so that example.com/blog/anything will redirect to blog.example.com/anything regardless of how many slashes or parameters the url contains. So even example.com/blog/a/b/c/d/e?google=true should redirect to blog.example.com/a/b/c/d/e?google=true

So far the following works if there is only one directory after blog:

  get '/blog/:what', to: redirect('http://blog.codeundercover.com/%{what}')

I, however, need this to work regardless of what text comes after /blog. How do I do this?

Upvotes: 1

Views: 2236

Answers (2)

Ultimation
Ultimation

Reputation: 1069

get "/blog(/*what)", to: redirect("http://blog.codeundercover.com/%{what}")

Upvotes: 0

Wes Foster
Wes Foster

Reputation: 8900

Your route is not using a wildcard route. Instead, it's what the Rails Routing Guide refers to as a Static Segment

You'll want to use Wildcard Globbing instead:

get '/blog/*what', to: redirect('http://blog.codeundercover.com/%{what}'), constraints: { what: /.*/ }

Upvotes: 2

Related Questions