Skip to content

Commit d63f288

Browse files
committed
Add a middleware to kill all bots that don't respect robots.txt
1 parent b83b29e commit d63f288

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

config/application.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
# you've limited to :test, :development, or :production.
1010
Bundler.require(*Rails.groups)
1111

12+
require './lib/bot_killer'
13+
1214
module RailsContributors
1315
class Application < Rails::Application
1416
# Initialize configuration defaults for originally generated Rails version.
@@ -17,5 +19,7 @@ class Application < Rails::Application
1719
# Settings in config/environments/* take precedence over those specified here.
1820
# Application configuration should go into files in config/initializers
1921
# -- all .rb files in that directory are automatically loaded.
22+
23+
config.middleware.insert 0, BotKiller
2024
end
2125
end

lib/bot_killer.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class BotKiller
2+
BLACKLISTED_BOTS = %r{
3+
FAST |
4+
MauiBot
5+
}xi
6+
7+
def initialize(app)
8+
@app = app
9+
end
10+
11+
def call(env)
12+
request = Rack::Request.new(env)
13+
14+
if request.user_agent =~ BLACKLISTED_BOTS
15+
[404, {}, ["Not found"]]
16+
else
17+
@app.call(env)
18+
end
19+
end
20+
end

test/integration/bot_killer_test.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
require 'test_helper'
2+
3+
class BotKillerTest < ActionDispatch::IntegrationTest
4+
test 'MauiBot is blacklisted' do
5+
get '/', headers: { 'User-Agent' => 'MauiBot ([email protected])' }
6+
assert_response :not_found
7+
end
8+
9+
test 'FAST Enterprise is blacklisted' do
10+
get '/', headers: { 'User-Agent' => 'FAST Enterprise Crawler/5.3.4 ([email protected])' }
11+
assert_response :not_found
12+
end
13+
14+
test 'other user agests are not blacklisted' do
15+
get '/', headers: { 'User-Agent' => 'Foo' }
16+
assert_response :ok
17+
end
18+
end

0 commit comments

Comments
 (0)