如何使用.htaccess限制外部访问,仅允许子域名访问脚本目录
Got it, let's figure out how to lock down your /scripts directory so only your example.com subdomains can access it, while external sites get a 404. I'll cover the two most common web servers here—Nginx and Apache—since those are what most folks use.
First, open up your Nginx server block config for example.com (usually found at /etc/nginx/sites-available/example.com or a similar path). Then add a dedicated location block for /scripts that checks the Referer header (browsers send this when loading resources from another page) to filter allowed requests.
location /scripts/ { # Allow requests from example.com itself or any of its subdomains if ($http_referer ~* "^https?://([a-z0-9-]+\.)?example\.com") { return 200; } # Block all other external requests with a 404 return 404; }
- The regex
^https?://([a-z0-9-]+\.)?example\.commatches bothexample.comand any subdomain (likeblog.example.comorapp.sub.example.com). - If you want to disallow direct access (only allow requests coming from your subdomain pages, not the main domain), remove the
?in the regex so it becomes^https?://[a-z0-9-]+\.example\.com. - Don't forget to test your config with
nginx -tand reload Nginx withsystemctl reload nginxafter making changes.
For Apache, we'll use mod_rewrite to enforce the restriction. First, make sure mod_rewrite is enabled (run a2enmod rewrite if it isn't already). Then add these rules to your root .htaccess file or your Apache virtual host config.
RewriteEngine On # Restrict /scripts to example.com subdomains only RewriteCond %{HTTP_REFERER} !^https?://([a-z0-9-]+\.)?example\.com [NC] RewriteRule ^scripts/ - [R=404,L]
- The
RewriteCondchecks if the referer does not matchexample.comor its subdomains (the!negates the match). The[NC]flag makes the match case-insensitive. - If the condition is met (external referer), the
RewriteRulereturns a 404 and stops processing further rules (Lflag). - To exclude the main domain and only allow subdomains, adjust the regex to
!^https?://[a-z0-9-]+\.example\.com [NC]. - Restart Apache with
systemctl restart apache2after applying changes.
- The
Refererheader can be spoofed, but this setup is more than enough for blocking casual hotlinking and unintended external access. If you need stricter control, you'd have to implement something like API keys or OAuth, but that's way more complex. - Test with your actual subdomains to make sure the regex works. You can use
curlto simulate requests:# Test allowed referer (should load the resource) curl -H "Referer: https://sub.example.com" https://example.com/scripts/your-script.js # Test external referer (should return 404) curl -H "Referer: https://otherdomain.com" https://example.com/scripts/your-script.js
内容的提问来源于stack exchange,提问作者sirlouis

