如何通过.htaccess实现example.com/abc到https://www.example.com/abc的重定向?
Fixing Non-WWW/HTTP to WWW/HTTPS Redirection for Specific Paths
Hey there! Let's get this redirection working properly for you. The core issue with your current .htaccess setup is the order of your rewrite rules—Apache processes rules from top to bottom, and your internal routing rule was running before the domain/HTTPS redirects, which could cause unexpected behavior (like the redirect not triggering as expected for paths like /abc).
Here's the corrected .htaccess code:
RewriteEngine On # 1. Redirect all non-WWW OR HTTP requests to HTTPS + WWW # This automatically handles example.com/abc → https://www.example.com/abc RewriteCond %{HTTP_HOST} !^www\. [OR] RewriteCond %{HTTPS} !=on RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L] # 2. Handle internal application routing (your original rule, now after redirects) RewriteCond $1 !^(index\.php|resources|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L,QSA]
What changed and why?
- Rule order matters: We moved the domain/HTTPS redirect to the top. This ensures every incoming request (including
/abc) first gets redirected to the correcthttps://www.example.comaddress before any internal application routing happens. - Combined redirect rule: We merged the non-WWW and HTTP checks into one rule using the
[OR]flag. This way, any request that's either missingwww.or using HTTP gets redirected to the fully qualified HTTPS + WWW URL, preserving the full path (like/abc). R=301flag: This is a permanent redirect, which is best for SEO and tells browsers to cache the redirect. If you're testing, you can useR=302(temporary) first to avoid caching issues, then switch to301once everything works.
Quick Notes:
- Replace
example.comwith your actual domain name. - Make sure your server has
mod_rewriteenabled (most shared hosts have this on by default). - Clear your browser cache before testing, since old redirects might be cached.
内容的提问来源于stack exchange,提问作者Shihas
相关产品推荐
相关产品推荐

