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

如何强制域名跳转至www?我的.htaccess配置无效求助

Fixing Non-WWW to WWW Redirect in .htaccess

I see the issue here—your non-WWW to WWW redirect isn't working because of the order of your rewrite rules! Let me break down what's wrong and how to fix it:

What's Wrong with Your Current Config

Your redirect rule is placed after your SPA routing rule that sends all requests to index.html, and that rule uses the [L] flag (which tells Apache to stop processing further rules once this one matches). Since almost all requests will hit that SPA rule first, your redirect never gets a chance to run. Also, you don't need to repeat RewriteEngine On twice—it only needs to be enabled once at the top.

Corrected .htaccess Config

Replace your existing code with this:

RewriteEngine On

# First handle non-WWW to WWW redirect (runs before SPA routing)
RewriteCond %{HTTP_HOST} ^shadyab.com [NC]
RewriteRule ^(.*)$ http://www.shadyab.com/$1 [L,R=301,NC]

# Then handle SPA routing (only if request isn't for a real file/directory)
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-d
RewriteRule ^ /index.html [L]

Key Changes Explained

  • Rule Order: We moved the redirect rule to the top so it runs first—any request coming in on shadyab.com will be redirected to the WWW version before hitting the SPA routing logic.
  • Simplified SPA Logic: Combined the two OR conditions into negated checks (!-f = not an existing file, !-d = not an existing directory) which is a cleaner, more standard way to write this common SPA routing pattern.
  • Removed Redundant Code: Got rid of the duplicate RewriteEngine On line to keep the config clean.

Important Testing Tip

Since you're using a 301 (Permanent Redirect), browsers will cache this redirect aggressively. If you still don't see the redirect working right away, test in a private/incognito window or clear your browser's cache to bypass old cached redirects.

内容的提问来源于stack exchange,提问作者S.M_Emamian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:10:33