如何在Nginx中检测并过滤HTTP_HOST以拦截内容盗用?
Got it, let's work through this problem step by step. Since the thief site is using Cloudflare, blocking IP addresses is totally useless here—they'll just cycle through other Cloudflare proxies. But since you've confirmed their requests send HTTP_HOST: www.thiefsite.com to your server, filtering this header with Nginx is exactly the right fix.
Core Idea
Nginx uses the $host variable, which directly maps to the client's HTTP_HOST request header. We can validate that this value matches your legitimate domain(s) and reject any requests that don't meet the criteria.
Basic Configuration (Single Legitimate Domain)
Add this check inside your Nginx server block for www.mywebsite.com:
server { listen 80; listen 443 ssl; server_name www.mywebsite.com; # Block requests where HTTP_HOST isn't your legitimate domain if ($host != 'www.mywebsite.com') { return 403 Forbidden; # Swap with 301 redirect to your site if you prefer } # Your existing site setup below root /var/www/mywebsite; index index.php index.html; location ~ \.php$ { fastcgi_pass unix:/run/php/php8.2-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }
For Multiple Legitimate Domains
If you also need to allow mywebsite.com or subdomains, use a case-insensitive regex match:
if ($host !~* ^(www.mywebsite.com|mywebsite.com|blog.mywebsite.com)$) { return 403 Forbidden; }
Scalable Option: Use the map Directive
For sites with many allowed domains, the map directive is cleaner and more efficient than stacking if statements. Add this in your main http block (outside any server blocks):
http { # Define allowed hosts (block all by default) map $host $is_allowed { default 0; www.mywebsite.com 1; mywebsite.com 1; shop.mywebsite.com 1; } server { listen 80; listen 443 ssl; server_name www.mywebsite.com mywebsite.com shop.mywebsite.com; # Block unauthorized requests if ($is_allowed = 0) { return 403 Forbidden; } # Rest of your site configuration... } }
Testing & Applying Changes
- Always validate your config before reloading to avoid downtime:
nginx -t - If the test passes, reload Nginx to activate the new rules:
systemctl reload nginx
Why This Works
The thief site is proxying requests to your server with their own domain (www.thiefsite.com) in the HTTP_HOST header. Nginx catches this mismatch and rejects the request immediately, while legitimate visitors will send your domain in HTTP_HOST and pass through normally.
If you'd rather redirect stolen traffic back to your site instead of blocking it, replace return 403 Forbidden with return 301 https://www.mywebsite.com$request_uri;—pick whichever fits your goals.
内容的提问来源于stack exchange,提问作者Cyber

