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

Angular项目部署后www域名访问空白,非www正常,求解决方案

问题分析

你遇到的核心问题是**base-href配置的绝对域名限制了资源加载范围**:

  • 部署时指定--base-href "https://example.com",会让Angular强制从https://example.com根目录请求JS、CSS等静态资源
  • 当用户访问www.example.com时,浏览器会尝试跨域请求https://example.com下的资源,要么被同源策略拦截,要么路径匹配失败,导致页面空白
  • 网页标题和favicon是直接写在index.html里的,不受base-href影响,所以能正常显示
解决方案

1. 修正构建命令的base-href配置

改用相对根路径/,让资源从当前访问的域名根目录加载,执行以下构建命令:

ng build --configuration production --base-href "/"

2. 验证构建结果

构建完成后,检查dist目录下的index.html,确保<base>标签为:

<base href="/">

3. 可选:服务器层面统一域名(推荐)

为避免双域名带来的SEO分散和用户混淆,建议在服务器配置301永久重定向,将其中一个域名指向主域名:

Nginx配置示例

# 将www.example.com重定向到example.com
server {
    listen 80;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl;
    server_name www.example.com;
    ssl_certificate /path/to/your/cert.pem;
    ssl_certificate_key /path/to/your/cert.key;
    return 301 https://example.com$request_uri;
}

Apache配置示例

在.htaccess文件中添加:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]

完成以上步骤后,无论用户访问example.com还是www.example.com,都能正常加载页面内容。

内容的提问来源于stack exchange,提问作者adil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 16:19:54