方法
- R
实例公共方法
redirect(*args, &block) 链接
将任意路径重定向到另一个路径
get "/stories" => redirect("/posts")
这会重定向用户,同时忽略请求的某些部分,包括查询字符串等。/stories
、/stories?foo=bar
等都会重定向到 /posts
。
默认情况下,重定向将使用 301 永久移动
状态代码。可以使用 :status
选项覆盖此设置
get "/stories" => redirect("/posts", status: 307)
你还可以使用提供的重定向参数中的插值
get 'docs/:article', to: redirect('/wiki/%{article}')
请注意,如果你返回一个没有前导斜杠的路径,则该 URL 会加上当前 SCRIPT_NAME 环境变量作为前缀。这通常是“/”,但在已挂载引擎中或将应用程序部署到网站的子目录时可能有所不同。
或者,你可以使用其他语法之一
重定向的块版本允许轻松封装与相关重定向关联的任何逻辑。根据你的块接受的参数数量,将 params 和 request 作为参数提供,或仅提供 params。字符串是必需的返回值。
get 'jokes/:number', to: redirect { |params, request|
path = (params[:number].to_i.even? ? "wheres-the-beef" : "i-love-lamp")
"http://#{request.host_with_port}/#{path}"
}
请注意,重定向块的 do end
语法将不起作用,因为 Ruby 会将该块传递给 get
而不是 redirect
。请改用 { ... }
。
重定向的选项版本允许你仅提供需要更改的 URL 部分,它还支持类似于第一个示例的路径插值。
get 'stores/:name', to: redirect(subdomain: 'stores', path: '/%{name}')
get 'stores/:name(*all)', to: redirect(subdomain: 'stores', path: '/%{name}%{all}')
get '/stories', to: redirect(path: '/posts')
这会重定向用户,同时仅更改请求的指定部分,例如最后一个示例中的 path
选项。/stories
、/stories?foo=bar
分别重定向到 /posts
和 /posts?foo=bar
。
最后,可以提供一个响应于调用的对象来重定向,这允许您重复使用常见的重定向路由。调用方法必须接受两个参数,params 和 request,并返回一个字符串。
get 'accounts/:name' => redirect(SubdomainRedirector.new('api'))
来源:显示 | 在 GitHub 上
# File actionpack/lib/action_dispatch/routing/redirection.rb, line 199 def redirect(*args, &block) options = args.extract_options! status = options.delete(:status) || 301 path = args.shift return OptionRedirect.new(status, options) if options.any? return PathRedirect.new(status, path) if String === path block = path if path.respond_to? :call raise ArgumentError, "redirection argument not supported" unless block Redirect.new status, block end