Using an htaccess file to rewrite a block page with Apache
Luke Hebert
- 2 minutes read - 318 wordsSometimes a single page on your site attracts unwanted traffic, scrapers, or hotlinkers, and you need to shut it down without touching the rest of the site. Apache’s mod_rewrite module makes this straightforward: you match the URI, return a 400 status, and optionally verify the referrer to block cross-domain requests.
Basic Block
The first rule set returns a 400 response for any request to the target path, regardless of where it came from.
ErrorDocument 400 "System Undergoing Maintenance"
RewriteEngine on
RewriteCond %{REQUEST_URI} ^/2014/01/judge-removes-children-illegally [NC]
RewriteRule .* - [R=400,L]A few things to note:
ErrorDocument 400sets the message the visitor sees. Swap in whatever text fits your situation.[NC]makes the URI match case-insensitive.[R=400,L]sends a 400 response and stops further rule processing.
Block with Referrer Check
If you only want to block requests that arrive from a different domain (hotlinking, for example), add a second condition that compares the HTTP_HOST against the HTTP_REFERER.
RewriteCond %{REQUEST_URI} ^/2014/01/judge-removes-children-illegally
RewriteCond %{HTTP_HOST}@@%{HTTP_REFERER} !^([^@]*)@@https?://\1/.*
RewriteRule .* - [R=400,L]Here the @@ acts as a delimiter between the host and the referrer so the regex can capture the host portion and verify that the referrer originates from the same domain. If the referrer does not match, the 400 fires.
Where to Put It
Drop these rules into your site’s .htaccess file (or the equivalent <Directory> block in your virtual host config). Make sure mod_rewrite is enabled and AllowOverride permits FileInfo directives if you are using .htaccess.
Test with curl -I or a browser before going live. A misconfigured RewriteCond can accidentally block legitimate traffic to other pages if the URI pattern is too broad.
Verifying the Result
curl -I https://example.com/2014/01/judge-removes-children-illegallyYou should see a 400 Bad Request status line and the custom message you defined in ErrorDocument. If you get a 200, the rule is not matching, and you should double-check the URI path and the [NC] flag.