如何用.htaccess将xxx.example.com重写为example.com/xxx/(已有HTTPS及WP规则)
How to Redirect Subdomains to Corresponding WordPress Posts (With Existing Rules)
Got it, let's get this subdomain redirect working smoothly alongside your existing HTTPS and WordPress rewrite rules. The key here is rule order—we need to make sure HTTPS enforcement runs first, then handle the subdomain redirect, and finally let WordPress take over for its own routing.
Here's the complete .htaccess code with your existing rules plus the new subdomain redirect:
# Force all traffic to HTTPS (your existing rule) RewriteEngine On RewriteCond %{HTTPS} !=on RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=302] # NEW: Redirect subdomains to corresponding WordPress posts # Capture the subdomain (e.g., "xxx" from xxx.example.com) RewriteCond %{HTTP_HOST} ^(?!www\.)([a-zA-Z0-9-]+)\.example\.com$ [NC] # Only redirect the root of the subdomain (avoid messing with subpaths) RewriteCond %{REQUEST_URI} ^/$ # Redirect to https://example.com/[subdomain]/ (matches your post slug) RewriteRule ^(.*)$ https://example.com/%1/ [L,R=302] # BEGIN WordPress (your existing default rules) <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress
Let's break down the new rules:
RewriteCond %{HTTP_HOST} ^(?!www\.)([a-zA-Z0-9-]+)\.example\.com$ [NC]: This captures any subdomain (excludingwww) fromxxx.example.comand stores it in the%1variable. The[NC]flag makes it case-insensitive.RewriteCond %{REQUEST_URI} ^/$: Ensures we only redirect the root URL of the subdomain (e.g.,https://xxx.example.com/instead ofhttps://xxx.example.com/some-page/—adjust this if you need to handle subpaths too).RewriteRule ^(.*)$ https://example.com/%1/ [L,R=302]: Redirects the request to your main domain's post path, using the captured subdomain as the post slug. The[L]flag stops processing further rules, andR=302is a temporary redirect (switch toR=301once you've tested everything and want a permanent redirect).
Important Notes:
- Replace
example.comwith your actual domain everywhere in the code. - Make sure your WordPress post slugs exactly match the subdomains (e.g., subdomain
xxx.example.commaps to posthttps://example.com/xxx/). If you need a different mapping, you'd need to add specific rewrite rules for each subdomain instead of the dynamic one above. - Test with
R=302first—browsers cache301redirects, which can make troubleshooting a pain if you need to adjust things. - Double-check that mod_rewrite is enabled on your server (it usually is for WordPress hosts, but if not, you may need to contact your provider).
内容的提问来源于stack exchange,提问作者Jerry
相关产品推荐
相关产品推荐

