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

.htaccess无法实现特定URL的www移除与Angular路由重定向

Angular应用.htaccess重定向配置解决方案

现有配置

RewriteEngine On

RewriteBase /

# 移除URL中的www前缀
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# 若请求的文件/目录不存在,转发至index.html
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.html [L]

目标重定向规则

  • https://www.example.com/a/anID 应重定向至 https://example.com/index.html
  • https://example.com/a/anID 应重定向至 https://example.com/index.html
  • https://www.example.com/index.html 应重定向至 https://example.com/index.html
  • https://example.com/index.html 应保持原URL不变

修改后的有效配置

RewriteEngine On
RewriteBase /

# 处理www域名下的index.html跳转
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^index\.html$ https://%1/index.html [R=301,L]

# 处理www域名下非文件/目录的请求跳转
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ https://%1/index.html [R=301,L]

# 处理非www域名下非文件/目录的请求跳转
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.html [R=301,L]

# 保留非www域名下的index.html原URL
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^index\.html$ - [L]

配置说明

  1. www域名的index.html处理:精准匹配该场景,直接重定向到非www域名的index.html,避免多余跳转。
  2. www域名的动态路由请求:针对不存在的文件/目录,直接跳转到非www域名的index.html,一步到位满足需求。
  3. 非www域名的动态路由请求:同样针对不存在的文件/目录,重定向到同域名的index.html。
  4. 保留原index.html地址:最后一条规则确保非www域名下的index.html请求不被修改,维持原URL。

内容的提问来源于stack exchange,提问作者Alex Ibrahim Ojea

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 19:34:51