.htaccess子域名Rewrite规则失效问题求助
Fixing Subdomain to Path Rewrite in .htaccess
Hey there! Let's break down why your current rewrite rule isn't working and get that subdomain-to-path redirect sorted out.
The Core Issue with Your Current Rule
Your existing RewriteRule ^(.*)\-(.*)$ is looking for hyphens in the URL path (like https://example.com/ccc-bb), but your goal is to match hyphens in the subdomain (like ccc-bb.example.com). That's why the rule isn't triggering at all—it's checking the wrong part of the URL!
Correct .htaccess Configuration
Here's a revised setup that targets the subdomain properly, along with explanations for each part:
<IfModule mod_rewrite.c> RewriteEngine On # Block access to hidden files (except well-known for things like Let's Encrypt) RewriteRule /\.|^\.(?!well-known/) - [F] # Rewrite subdomains like ccc-bb.example.com to example.com/project/show/ccc/bb # 1. Skip the main domain to avoid redirect loops RewriteCond %{HTTP_HOST} !^example\.com$ # 2. Capture the two parts of the hyphen-separated subdomain RewriteCond %{HTTP_HOST} ^([^-]+)-([^.]+)\.example\.com$ # 3. Redirect to the target path, preserving any additional URL path if present # Use R=302 for testing, switch to R=301 for permanent redirects in production RewriteRule ^(.*)$ https://example.com/project/show/%1/%2/$1 [L,R=302] # Front controller: Route non-file/directory requests to your app's entry point RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] </IfModule>
Key Details to Note
- Matching the Subdomain: We use
%{HTTP_HOST}to access the full domain the user requested. The regex^([^-]+)-([^.]+)\.example\.com$grabs the two segments before the hyphen (e.g.,cccandbbfromccc-bb.example.com). - Avoiding Loops: The first
RewriteCondskips the mainexample.comdomain, so we don't end up redirecting in circles. - Preserving Paths: The
$1in theRewriteRulecaptures any additional path from the subdomain URL (e.g.,https://ccc-bb.example.com/aboutbecomeshttps://example.com/project/show/ccc/bb/about). - Redirect Type: Use
R=302(temporary) while testing, then switch toR=301(permanent) once you confirm everything works—permanent redirects get cached by browsers, so it's best to test first.
Additional Checks
- Make sure your server allows
.htaccessoverrides: In your Apache virtual host config, setAllowOverride Allfor your website's directory. - Clear your browser cache (or use incognito mode) when testing—old redirects might be cached and interfere with new rules.
- Double-check that
mod_rewriteis enabled on your server (the<IfModule>block will skip the rules if it's not, so you might want to verify with your host if needed).
内容的提问来源于stack exchange,提问作者Valentin Emil Cudelcu
相关产品推荐
相关产品推荐

