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

如何配置指向VPS的Angular应用路由以解决页面刷新错误?

Angular单页应用Apache环境刷新404问题解决

你的推测完全正确:Angular使用前端路由,应用内跳转由JS处理,不会向服务器发送新请求;但刷新页面时,浏览器会直接向Apache请求/home这类路径,而服务器上不存在对应的物理文件,因此返回404错误。.htaccess是解决该问题的常用方案,具体操作如下:

1. 启用Apache重写模块

首先确保Apache的rewrite模块已启用,执行以下命令:

sudo a2enmod rewrite
sudo systemctl restart apache2

2. 配置重写规则(两种方式选其一)

方式一:使用.htaccess文件

在Angular应用的部署目录(例如/var/www/mydomain.example)下创建或修改.htaccess文件,添加以下规则:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  # 不对index.html本身进行重写
  RewriteRule ^index\.html$ - [L]
  # 匹配非实际存在的文件或目录请求
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  # 将请求重定向到index.html,由Angular路由处理
  RewriteRule . /index.html [L]
</IfModule>

方式二:直接修改Apache站点配置(更推荐)

打开站点配置文件(例如/etc/apache2/sites-available/mydomain.example.conf),在<Directory /var/www/mydomain.example>代码块中添加重写规则:

<Directory /var/www/mydomain.example>
    # 保留原有配置...
    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteBase /
        RewriteRule ^index\.html$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /index.html [L]
    </IfModule>
</Directory>

修改完成后重启Apache:

sudo systemctl restart apache2

核心逻辑说明

两种方式的本质相同:让Apache将所有非静态资源的请求(即不存在的文件/目录路径)转发到index.html,由Angular的前端路由系统解析路径并渲染对应组件,从而解决刷新页面时的404问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 22:36:06