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

移除AngularJS URL哈希后页面刷新失效问题求助

Why Removing AngularJS URL Hash Causes 404 on Refresh/Direct Access, and How to Fix It

Hey there! Let's break down why you're hitting that frustrating 404 error, and how to fix it for good.

The Root Cause

When you used $locationProvider.html5Mode(true) to strip the hash (#) from your AngularJS URLs, you switched to HTML5 History Mode. Here's the key issue: AngularJS handles all routing on the client side. Those clean URLs like /dashboard or /user/123 don't point to actual files or endpoints on your web server—they're just virtual routes managed by your AngularJS app.

When you refresh the page or paste a direct URL into the browser, the browser doesn't know this is a client-side route. It sends a request straight to your server asking for the resource at that path (e.g., yourdomain.com/dashboard). Since your server doesn't have a file or backend endpoint matching /dashboard, it throws a 404 error.

The Fix: Redirect All Requests to index.html

The solution is to configure your web server to forward every request for a client-side route to your app's main index.html file. This way, AngularJS loads first, then takes over and routes the user to the correct view.

Here are examples for common server setups:

Apache

Create a .htaccess file in your app's root directory with these rules:

RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

This tells Apache to serve existing files/directories normally, but redirect all other requests to index.html.

Nginx

Add this snippet to your server block configuration:

location / {
    try_files $uri $uri/ /index.html;
}

The try_files directive checks if the requested path exists as a file or directory—if not, it serves index.html instead.

Node.js (Express)

Add this middleware after setting up static file serving:

const express = require('express');
const app = express();

// Serve static assets from your app's public folder
app.use(express.static(__dirname + '/public'));

// Redirect all non-static requests to index.html
app.get('*', (req, res) => {
    res.sendFile(__dirname + '/public/index.html');
});

app.listen(3000);

Don't Skip the Base Tag!

Make sure you've added the <base> tag in your index.html <head> section—it helps AngularJS resolve routes correctly in HTML5 mode:

<base href="/">

That should eliminate those 404 errors when refreshing or accessing URLs directly. Give it a test run!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:29:56