如何强制域名跳转至www?我的.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.comwill be redirected to the WWW version before hitting the SPA routing logic. - Simplified SPA Logic: Combined the two
ORconditions 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 Online 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

