Skip to content

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.rb
index 2794a92649b..2ce859622fd 100644
--- a/app/controllers/search_controller.rb
+++ b/app/controllers/search_controller.rb
@@ -1,6 +1,7 @@
# frozen_string_literal: true
class SearchController < ApplicationController
+ before_action :block_crawler, only: :show
before_action :cancel_overloaded_search, only: [:query]
skip_before_action :check_xhr, only: :show
after_action :add_noindex_header
@@ -212,6 +213,26 @@ class SearchController < ApplicationController
false
end
+ 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_search
render_json_error I18n.t("search.extreme_load_error"), status: 409 if site_overloaded?
end
diff --git a/spec/requests/search_controller_spec.rb b/spec/requests/search_controller_spec.rb
index 760b78b6034..ac21d430c5b 100644
--- a/spec/requests/search_controller_spec.rb
+++ b/spec/requests/search_controller_spec.rb
@@ -303,6 +303,15 @@ RSpec.describe SearchController do
end
end
end
+
+ 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
+ end
end
describe "#show" do