Nginx通配符子域名未映射至指定路径问题求助
Hey there! Let's work through your Nginx wildcard subdomain issue. From what you shared, you want all xxx.domain.com subdomains to map to a specific target, while already having rules for specific subdomains like 1.domain.com and workspace.domain.com. Let's refine your setup to be cleaner and more reliable—Nginx works best when we avoid overusing if statements, so here's a structured approach:
1. Handle Specific Subdomains First
Create separate server blocks for your unique subdomains (like 1.domain.com and workspace.domain.com). This keeps your rules clear and avoids conflicts with the wildcard:
server { listen 80; listen [::]:80; server_name 1.domain.com; root /var/www/domain.com/web/; # Your existing rewrite rule, excluding protected paths rewrite ^(?!/(1|stats|error|\.well-known/acme-challenge))/(.*)$ /1/$2 last; # Basic static file handling location / { try_files $uri $uri/ =404; } } server { listen 80; listen [::]:80; server_name workspace.domain.com; root /var/www/domain.com/web/; # Complete your workspace rewrite rule here (your original code was truncated) # Example matching your existing pattern: rewrite ^(?!/(workspace|stats|error|\.well-known/acme-challenge))/(.*)$ /workspace/$2 last; location / { try_files $uri $uri/ =404; } }
2. Configure Wildcard Subdomains
Next, make a dedicated server block for all other xxx.domain.com subdomains. You can either map them to a dynamic directory based on the subdomain, or redirect them to a fixed location:
server { listen 80; listen [::]:80; server_name *.domain.com; root /var/www/domain.com/web/; # Option 1: Map subdomain to a matching directory (e.g., xxx.domain.com/foo → /xxx/foo) set $subdomain ""; if ($host ~* "^(.*)\.domain\.com$") { set $subdomain $1; } rewrite ^/(.*)$ /$subdomain/$1 last; # Option 2: Redirect all wildcard subdomains to your main domain (uncomment if needed) # return 301 https://domain.com$request_uri; location / { try_files $uri $uri/ =404; } }
3. Main Domain & www Handling
Finally, keep a server block for your primary domain and www variant:
server { listen 80; listen [::]:80; server_name domain.com www.domain.com; root /var/www/domain.com/web/; location / { try_files $uri $uri/ =404; } # Optional: Redirect www to non-www (uncomment if desired) # if ($host = www.domain.com) { # return 301 https://domain.com$request_uri; # } }
Key Notes to Remember
- DNS Setup: Make sure you have a wildcard A (or AAAA) record
*.domain.compointing to your server's IP—without this, wildcard subdomains won't resolve to your Nginx instance. - HTTPS: If you're using SSL, add
listen 443 ssl;to each server block, and use a wildcard SSL certificate (*.domain.com) that covers all subdomains. - Avoid
ifWhere Possible: Nginx'sifdirective can cause unexpected behavior in some contexts. Splitting into separate server blocks is the official recommended approach for clarity and reliability.
内容的提问来源于stack exchange,提问作者ddouma

