如何通过.htaccess将子域名及主域名特定路径重定向至指定URL?
Got it, let's break down how to implement these redirects properly—with SEO best practices front and center (using permanent 301 redirects to preserve link equity). I’ll cover both Apache (the most common setup for PHP sites) and Nginx configurations, since you didn’t specify your server type.
Apache Setup (Using .htaccess)
First, confirm that mod_rewrite is enabled on your server. Then create or edit the .htaccess file in your site’s root directory (where index.php lives) with these rules:
RewriteEngine On # Redirect abc.xxx.com (root request only) to abc.xxx.com/index.php?id=abc RewriteCond %{HTTP_HOST} ^abc\.xxx\.com$ RewriteRule ^$ /index.php?id=abc [R=301,L] # Redirect www.xxx.com/abc and xxx.com/abc to abc.xxx.com/index.php?id=abc RewriteCond %{HTTP_HOST} ^(www\.)?xxx\.com$ RewriteRule ^abc/?$ https://abc.xxx.com/index.php?id=abc [R=301,L]
Rule Breakdown:
- First rule: Targets only the root request of
abc.xxx.com(the^$matches an empty path after the domain). TheR=301flag tells search engines this is a permanent redirect, andLstops processing further rules once this one runs. - Second rule: Matches both
www.xxx.comandxxx.com(the(www\.)?makes the "www" optional). It catches/abcwith or without a trailing slash (/?), then redirects directly to your desired subdomain URL—keeping theabcidentifier intact for SEO.
Nginx Setup
If you’re using Nginx, edit your server block configuration (typically in /etc/nginx/sites-available/ or similar) with these rules:
# Handle abc.xxx.com redirect server { listen 80; listen [::]:80; server_name abc.xxx.com; # Redirect root request to index.php?id=abc location = / { return 301 $scheme://abc.xxx.com/index.php?id=abc; } # Your existing PHP handler config goes here (e.g., passing requests to PHP-FPM) location ~ \.php$ { # Example: fastcgi_pass unix:/run/php/php8.2-fpm.sock; # Add your existing PHP processing rules here } } # Handle main domain /abc redirects server { listen 80; listen [::]:80; server_name www.xxx.com xxx.com; # Redirect /abc (with or without trailing slash) location = /abc { return 301 https://abc.xxx.com/index.php?id=abc; } location = /abc/ { return 301 https://abc.xxx.com/index.php?id=abc; } # Rest of your main domain configuration }
Critical SEO Notes:
- Permanent 301 redirects are non-negotiable here—they signal to search engines that the old URLs have permanently moved, so they’ll update their indexes and pass link equity to the target URL.
- The target URL retains the
abcsubdomain and includesid=abc, which preserves the identifier you wanted to keep for SEO. - We only match the exact paths you specified, so other pages on your site won’t be affected by these redirects.
If you run into issues adapting this to your server, or need adjustments for HTTPS (just swap http:// with https:// or add SSL configs), feel free to ask!
内容的提问来源于stack exchange,提问作者Mehran Ishanian

