Phil Gyford
Phil Gyford

Reputation: 14634

Redirecting a path to a new domain in Rails routes

I want to redirect requests for a bunch of files/folders in a directory on one site to a directory (and then identical path) on a new site.

In my Rails routes.rb I have:

match '/uploads/*path', :to => redirect{|params, request| "http://othersite.com/uploads/#{params[:path]}"}

which I've got from this answer.

It almost works, except this URL:

http://currentsite.com/uploads/some/directories/filename.pdf

redirects to:

http://othersite.com/uploads/some/directories/filename

I can't work out why the file extension is missing.

(I would also add something like constraints: {:path => /[\w\-_\/]+(\.[a-z]+)?/} to the end to ensure the path is vaguely valid, but I've left that off while trying to fix this issue.)

Upvotes: 3

Views: 1422

Answers (1)

Winfield
Winfield

Reputation: 19145

You want to include the request format:

match '/uploads/*path', :to => redirect{|params, request| "http://othersite.com/uploads/#{params[:path]}#{ '.'+params[:format] if params[:format].present? }"}

... this is the portion of the URI we think of as the file extension (ie: .pdf in your example).

Though, it may be more elegant to just use the full incoming request path (via request.full_path, which has the URI path and all query params):

match '/uploads/*path', :to => redirect{|params, request| "http://othersite.com/uploads/#{ request.fullpath }" }

Upvotes: 6

Related Questions