Apache's Location
directive provides a clean way to handle specific URLs without involving rewrite rules or additional modules. Here's the most straightforward solution:
Redirect 404 /
For more control over the response, combine Deny
with custom error handling:
Require all denied
ErrorDocument 403 /errors/404.html
When dealing with multiple paths, use LocationMatch
with regex patterns:
Redirect 404 /
The Location directive is processed early in Apache's request cycle, making it more efficient than rewrite rules for simple denial cases. However, ensure you're not overusing this pattern for large numbers of URLs.
Here's a complete virtual host configuration that blocks specific API endpoints:
ServerName example.com
Redirect 404 /
Require all denied
ErrorDocument 403 "This resource no longer exists"
- Always test with
curl -I
to verify response codes - Check Apache error logs if the directive isn't working
- Remember to reload Apache after configuration changes
When managing web servers, there are legitimate cases where you need to explicitly return a 404 (Not Found) status for specific URLs. This might be for:
- Deprecated API endpoints
- Temporary disabled features
- Security through obscurity
- Preventing crawlers from indexing certain paths
The simplest way without involving mod_rewrite is using the SetHandler
directive with none
:
<Location "/some/url">
SetHandler none
Require all denied
</Location>
Using ErrorDocument
<Location "/legacy-api">
ErrorDocument 404 "This resource no longer exists"
RewriteEngine On
RewriteRule .* - [R=404,L]
</Location>
With mod_alias
Alias /nonexistent /dev/null
<Location "/nonexistent">
Require all denied
</Location>
The SetHandler none
approach is most efficient because:
- No module dependencies
- Minimal configuration
- Handled early in request processing
After implementing, verify with curl:
curl -I https://yourdomain.com/some/url
Should return:
HTTP/1.1 404 Not Found