A platform for community discussion. Free, open, simple.
DEV: Prevent crawlers from loading search results. (#31535)
Gary Pendergast38de3d7bd1f5
diff --git a/app/controllers/search_controller.rb b/app/controllers/search_controller.rbindex 2794a92649b..9e96771f55f 100644--- a/app/controllers/search_controller.rb+++ b/app/controllers/search_controller.rb@@ -34,6 +34,25 @@ class SearchController < ApplicationControllerraise Discourse::InvalidParameters.new("page parameter must not be greater than 10")end+ if request.user_agent &&+ CrawlerDetection.crawler?(request.user_agent, request.headers["HTTP_VIA"])+ 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"++ return(render html: crawler_html.html_safe, layout: false, content_type: "text/html")+ end+discourse_expires_in 1.minutesearch_args = {diff --git a/spec/requests/search_controller_spec.rb b/spec/requests/search_controller_spec.rbindex 7b8edb37c8d..50238efb2bf 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