方法
- R
实例公共方法
redirect(*args, &block) 链接
将任何路径重定向到另一条路径
get "/stories" => redirect("/posts")
这将重定向用户,同时忽略请求的某些部分,包括查询字符串等。/stories、/stories?foo=bar 等都会重定向到 /posts。
默认情况下,重定向将使用 301 Moved Permanently 状态码。这可以通过 :status 选项来覆盖。
get "/stories" => redirect("/posts", status: 307)
您还可以在提供的重定向参数中使用插值。
get 'docs/:article', to: redirect('/wiki/%{article}')
请注意,如果您返回的路径没有前导斜杠,则 URL 将以当前 SCRIPT_NAME 环境变量为前缀。这通常是 ‘/’,但在挂载的引擎或应用程序部署到网站子目录的情况下可能不同。
或者,您可以使用其他语法之一。
redirect 的块版本允许轻松封装与特定重定向相关的任何逻辑。根据您的块接受的参数数量,将 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。请改用 { ... }。
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。
最后,可以将响应 call 的对象提供给 redirect,从而允许您重用常见的重定向路由。call 方法必须接受两个参数:params 和 request,并返回一个字符串。
get 'accounts/:name' => redirect(SubdomainRedirector.new('api'))
来源: 显示 | 在 GitHub 上
# File actionpack/lib/action_dispatch/routing/redirection.rb, line 206 def redirect(*args, &block) options = args.extract_options! status = options.delete(:status) || 301 path = args.shift source_location = caller[0] if ActionDispatch.verbose_redirect_logs return OptionRedirect.new(status, options, source_location) if options.any? return PathRedirect.new(status, path, source_location) if String === path block = path if path.respond_to? :call raise ArgumentError, "redirection argument not supported" unless block Redirect.new status, block, source_location end