简体   繁体   中英

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\\-_\\/]+(\\.[az]+)?/} to the end to ensure the path is vaguely valid, but I've left that off while trying to fix this issue.)

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 }" }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM