如何从/:id 重定向到/:friendly_id [英] How to redirect from /:id to /:friendly_id
本文介绍了如何从/:id 重定向到/:friendly_id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当有人尝试使用旧的 /:id
URL 而不是首选的 /:friendly_id
链接浏览页面时,是否可以强制进行 301 重定向?
Is is possible to force a 301 redirect when someone attempts to browse to a page using the old /:id
URL, rather than than the preferred /:friendly_id
link?
显然,此类重定向有助于告诉 Google 您已更新链接...因此它停止显示旧的非友好链接.
Apparently such redirections help to tell Google that you have updated the link.. so it stops displaying the old non-friendly link.
推荐答案
使用最新版本的 friendly_id (5.0.3 at撰写此答案的时间)和 Rails 4,我在控制器中执行此操作:
With the latest version of friendly_id (5.0.3 at the time of writing this answer) and Rails 4, I do this in the controller:
class ItemsController < ApplicationController
before_action :set_item, only: [:show, :edit, :update, :destroy]
...
private
def set_item
@item = Item.friendly.find(params[:id])
redirect_to action: action_name, id: @item.friendly_id, status: 301 unless @item.friendly_id == params[:id]
end
end
以下是 redirect_to
行的描述,逐条分解:
Here's a description of the redirect_to
line, broken down piece by piece:
action: action_name
保留您要连接到的操作(可以根据现有的before_action
显示、编辑、更新或销毁),以便如果您正在访问/items/1/edit
,您将被重定向到/items/pretty-url/edit
id: @item.friendly_id
确保您被重定向到的 URL 是漂亮的 URLstatus: 301
将重定向设置为 301 的状态,用于 SEO除非@item.friendly_id == params[:id]
确保我们不会重定向通过其漂亮 URL 访问@item
的人
action: action_name
retains the action that you're connecting to (which can be show, edit, update, or destroy based on thebefore_action
that's in place) so that if you're accessing/items/1/edit
you will be redirected to/items/pretty-url/edit
id: @item.friendly_id
ensures that the URL you're being redirected to is the pretty URLstatus: 301
sets the redirect to the status of 301, for SEOunless @item.friendly_id == params[:id]
makes sure that we're not redirecting people who access@item
through its pretty URL
这篇关于如何从/:id 重定向到/:friendly_id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文