You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.htaccess配置:非www转www并指向子目录及跳转异常解决

Fixing Non-WWW to WWW Redirect + Subdirectory Routing in .htaccess

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 exactly yourdomain.com (the [NC] makes it case-insensitive, so it matches YourDomain.com too).
    • RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R=301,L]: Redirects any request path ($1 captures everything after the domain) to the www version. R=301 is a permanent redirect (good for SEO), and L tells 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.com with your actual domain, and your-subdirectory with 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 On will 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:48:38