web.config重定向规则修改:保留原请求顶级域名的技术问询
Hey there! Let’s tackle this redirect problem step by step. From what you’ve described, you want every incoming request—whether it’s a main domain or subdomain on tld1 or tld2—to redirect to domain1 on the same TLD as the original request. So anything.tld2 goes to domain1.tld2, and sub.domain1.tld1 stays within tld1 pointing to domain1.tld1.
Below are solutions for the most common environments you’re likely using:
Nginx Configuration
If you’re running Nginx, regex-based server name matching lets you capture the TLD and redirect accordingly:
# Match all domains/subdomains on tld1 and tld2 (HTTP) server { listen 80; listen [::]:80; server_name ~^(?<any_part>.+)\.(?<tld>tld1|tld2)$ ~^(?<tld>tld1|tld2)$; # Redirect to domain1.[captured TLD], keeping original path/params return 301 https://domain1.$tld$request_uri; } # Repeat for HTTPS (add your SSL cert config) server { listen 443 ssl; listen [::]:443 ssl; server_name ~^(?<any_part>.+)\.(?<tld>tld1|tld2)$ ~^(?<tld>tld1|tld2)$; ssl_certificate /path/to/your/cert.pem; ssl_certificate_key /path/to/your/key.pem; return 301 https://domain1.$tld$request_uri; }
- The regex captures both subdomains and root domains, pulling the TLD into the
$tldvariable. $request_uriensures any path or query parameters from the original request are preserved.
Apache Configuration (with mod_rewrite)
For Apache, enable mod_rewrite and add this to your .htaccess or server config:
RewriteEngine On # Capture the TLD from the incoming hostname (matches tld1/tld2) RewriteCond %{HTTP_HOST} ^.*\.(tld1|tld2)$ [NC] # Redirect to domain1.[captured TLD], keeping the request path RewriteRule ^(.*)$ https://domain1.%2/$1 [R=301,L]
%2refers to the second captured group in theRewriteCond(your target TLD).[NC]makes the match case-insensitive, and[L]stops processing further rules after this one.
Cloudflare Workers (If Using CDN)
If you manage domains through Cloudflare, a Worker can handle this redirect logic globally:
addEventListener('fetch', event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { const url = new URL(request.url) const hostnameParts = url.hostname.split('.') // Grab the TLD (last part of the hostname) const tld = hostnameParts.pop() // Only redirect for our target TLDs if (['tld1', 'tld2'].includes(tld)) { const newUrl = `https://domain1.${tld}${url.pathname}${url.search}` return Response.redirect(newUrl, 301) } // Pass through requests for other TLDs as normal return fetch(request) }
Key Tips to Avoid Headaches
- SSL Certificates: Use a wildcard certificate (like
*.tld1) or multi-domain SAN certificate to cover all your domains/subdomains. - Test with 302 First: Use temporary redirects (
302) during testing to avoid browser caching issues—switch to301once everything works. - DNS Checks: Ensure every domain/subdomain you want to redirect is pointed to your server or Cloudflare.
内容的提问来源于stack exchange,提问作者Shaggy

