Nginx配置问题:除指定域名及子域名外均返回404
Ah, I see the issue here—your current configuration is targeting the wrong part of the request! Let's break down what's going wrong and how to fix it.
Root Cause of the Problem
The location directive in Nginx matches against the request URI (the path part of the URL)—not the domain name (Host header). Your regex ~ ^(?!(.?)examplesite.com/?(.*)) is checking if the path doesn't start with examplesite.com, which is true for almost every request (since paths start with /). That's why even requests to examplesite.com are hitting the 404 rule.
Correct Solutions
Option 1: Use Separate Server Blocks (Recommended)
This is the most idiomatic Nginx approach—split your configuration into two server blocks to handle valid domains and all others separately:
# Handle examplesite.com and all its subdomains server { listen 80; # Update to 443 if using HTTPS, and add SSL cert config server_name examplesite.com *.examplesite.com; location / { return 302 https://192.168.1.1/index.html; } } # Default server: Return 404 for all other domains server { listen 80 default_server; # Update to 443 default_server for HTTPS server_name _; # Matches any host not covered by other server blocks location / { return 404; } }
- The first server block catches all requests to
examplesite.comand any subdomain (likesub.examplesite.com), then redirects them to your local server. - The default server block handles every other domain request and returns a 404.
Option 2: Single Server Block with Host Check
If you need to keep everything in one server block, use an if directive to check the $host variable (which holds the domain name from the request header):
server { listen 80; # Adjust for HTTPS as needed server_name _; # Or list your actual server names here # Reject any request not targeting examplesite.com or its subdomains if ($host !~* ^(.+\.)?examplesite\.com$) { return 404; } # Redirect valid requests to your local server location / { return 302 https://192.168.1.1/index.html; } }
- The regex
^(.+\.)?examplesite\.com$matchesexamplesite.comdirectly, plus any subdomain (likeblog.examplesite.comorapp.sub.examplesite.com). - Note: While
ifis generally discouraged in Nginx for complex logic, this simple host check is safe to use.
Key Takeaway
Always remember: location blocks match the request path, not the domain. To filter by domain, use either separate server blocks or check the $host variable.
内容的提问来源于stack exchange,提问作者stefs




