.htaccess配置:非www转www并指向子目录及跳转异常解决
Hey there! Let's get this sorted out. The main issue here is almost certainly rule order—you need to handle the non-www → www redirect first, before routing traffic to your subdirectory. If you do it the other way around, the subdirectory rule can "override" the domain redirect, which is why you're seeing the non-www domain stick around.
Here's a complete .htaccess snippet that should do exactly what you need:
# Enable mod_rewrite RewriteEngine On # 1. Redirect non-www to www (301 permanent redirect for SEO) RewriteCond %{HTTP_HOST} ^yourdomain\.com$ [NC] RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R=301,L] # 2. Redirect root domain to subdirectory (without changing the URL in the browser) RewriteCond %{REQUEST_URI} !^/your-subdirectory/ RewriteRule ^(.*)$ /your-subdirectory/$1 [L]
Let me break down what each part does:
- RewriteEngine On: Turns on the URL rewriting module—required for all these rules to work.
- Non-www to www redirect:
RewriteCond %{HTTP_HOST} ^yourdomain\.com$ [NC]: Checks if the requested domain is exactlyyourdomain.com(the[NC]makes it case-insensitive, so it matchesYourDomain.comtoo).RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R=301,L]: Redirects any request path ($1captures everything after the domain) to the www version.R=301is a permanent redirect (good for SEO), andLtells Apache to stop processing further rules once this one runs.
- Subdirectory routing:
RewriteCond %{REQUEST_URI} !^/your-subdirectory/: Makes sure we don't redirect if the request is already pointing to the subdirectory (prevents infinite loops).RewriteRule ^(.*)$ /your-subdirectory/$1 [L]: Routes all incoming requests to your subdirectory, while keeping the original URL visible in the browser.
Important Notes:
- Replace
yourdomain.comwith your actual domain, andyour-subdirectorywith the name of your target subdirectory. - Make sure mod_rewrite is enabled on your server (most shared hosts have this turned on by default, but if not, you might need to contact your host—adding
RewriteEngine Onwill throw an error if it's unavailable). - Test the redirects thoroughly—clear your browser cache first, since 301 redirects get cached by browsers.
If you had existing rules for the subdirectory redirect, make sure you replace them with the above (or reorder them so the non-www → www rule comes first). That should fix the issue where adding www still shows the non-www domain!
内容的提问来源于stack exchange,提问作者Kim Carlo

