LoginSignup
31
30

More than 5 years have passed since last update.

redirect_toのレスポンスコードをデフォルトで302 Foundではなく301 Moved Permanentlyにする

Last updated at Posted at 2013-11-15

302じゃなくて301を使う理由は、301リダイレクトと302リダイレクトの違い参照。

重要なところを抜き出すと、

301リダイレクトは、”Permanent Redirect”で「恒久的な転送」、一方、302リダイレクトは、”Temporary Redirect”で「一時的な転送」を表します。

検索エンジンのインデックスに関して:

  • 302リダイレクト:旧URLのまま
  • 301リダイレクト:新URLへ

というようになっている。

ちなみにRailsでは、デフォルトで302が返るようになっている。
これを変えるには、

redirect_to root_path, status: :moved_permanently
redirect_to root_path, status: 301

とすれば良いのだが、自分が通常redirectしているところでは、新しいURLに移動などが多いので、移動先のURLを検索エンジンがインデックスしてくれて構わない。なので301をデフォルトにする用に書き換えておきたい。

そのためには、アプリケーションコントローラーに以下のコードを書けばOK。
(alias_method_chainの枠組みに乗ったため、ちょっと関数名が変だが、どうせredirect_toしか使わないので気にしない。)

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  def redirect_to_with_moved_permanently(options = {}, response_status = {})
    response_status.reverse_merge!(status: :moved_permanently)
    redirect_to_without_moved_permanently(options, response_status)
  end
  alias_method_chain :redirect_to, :moved_permanently
end

これで、デフォルトで301になり、

redirect_to root_path, status: :found
redirect_to root_path, status: 302

等と書いた時だけ302を返すようになる。

ちなみに、元のredirect_toのコード以下にあるので、ご参照あれ。
https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/redirecting.rb

ちなみに

301 のリダイレクトは、Rails的にはrouterを使うことを推奨している模様。

config/routes.rb
  get "/hoge" => redirect("/fuga")

これだと、デフォルトで301になる。

自分の考えたケースだと、controllerのredirect_toも301デフォルトの方が良いと思ったけれど、それで良いかは自己責任でお願いします。

31
30
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
30