A platform for community discussion. Free, open, simple.
DEV: Prevent crawlers from loading search results. (#31553)
Gary Pendergast5f3ffdc4a46c
diff --git a/app/controllers/search_controller.rb b/app/controllers/search_controller.rbindex 2794a92649b..2ce859622fd 100644--- a/app/controllers/search_controller.rb+++ b/app/controllers/search_controller.rb@@ -1,6 +1,7 @@# frozen_string_literal: trueclass SearchController < ApplicationController+ before_action :block_crawler, only: :showbefore_action :cancel_overloaded_search, only: [:query]skip_before_action :check_xhr, only: :showafter_action :add_noindex_header@@ -212,6 +213,26 @@ class SearchController < ApplicationControllerfalseend+ def block_crawler+ if use_crawler_layout?+ crawler_html = <<~HTML+ <!DOCTYPE html>+ <html>+ <head>+ <meta name='robots' content='noindex'>+ </head>+ <body>+ <p><em>*waves hand*</em> This is not the content you are looking for</p>+ </body>+ </html>+ HTML++ response.headers["X-Robots-Tag"] = "noindex"++ render html: crawler_html.html_safe, layout: false, content_type: "text/html"+ end+ end+def cancel_overloaded_searchrender_json_error I18n.t("search.extreme_load_error"), status: 409 if site_overloaded?enddiff --git a/spec/requests/search_controller_spec.rb b/spec/requests/search_controller_spec.rbindex 760b78b6034..ac21d430c5b 100644--- a/spec/requests/search_controller_spec.rb+++ b/spec/requests/search_controller_spec.rb@@ -303,6 +303,15 @@ RSpec.describe SearchController doendendend++ context "when visited by a crawler" do+ it "responds with a noindex page" do+ get "/search", params: { q: "test" }, headers: { "HTTP_USER_AGENT" => "Googlebot" }+ expect(response.status).to eq(200)+ expect(response.headers["X-Robots-Tag"]).to eq("noindex")+ expect(response.body).to include("<meta name='robots' content='noindex'>")+ end+ endenddescribe "#show" do