Angular 1.x项目Ui Router页面刷新问题及相关配置说明
Hey there, let's work through this UI-Router refresh problem you're hitting. I've dealt with exactly this scenario in Angular 1.x projects before, so here's the breakdown of what's happening and how to fix it.
Why the Refresh Problem Happens
When you refresh the page (say, on /admin/cats), your browser sends a direct request to your server for that URL. But since Angular's routing is client-side only, your server doesn't have a physical file or endpoint matching /admin/cats—so it throws a 404 error. The fix requires configuring your server to route all these client-side paths back to your Angular app's main index.html file.
Step-by-Step Solutions
1. Configure Server Rewrite Rules
This is the core fix. You need to tell your server to redirect all requests under /admin/ (that aren't for actual files or directories) to /admin/index.html. Here's how to do it for common servers:
Apache (using .htaccess)
Create or update the .htaccess file in your project's root (or the /admin/ directory) with this:
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase /admin/ # Don't rewrite requests for index.html itself RewriteRule ^index\.html$ - [L] # Skip actual files/directories RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Redirect everything else to index.html RewriteRule . /admin/index.html [L] </IfModule>
Nginx
Add this location block to your Nginx configuration:
location /admin/ { # Try to serve the requested file first, then the directory, then fall back to index.html try_files $uri $uri/ /admin/index.html; }
Node.js (Express)
If you're using Express as your server, add these middleware rules:
// Serve static files from your Angular app's public directory app.use('/admin', express.static(__dirname + '/path/to/your/angular/public')); // Catch all routes under /admin and send index.html app.get('/admin/*', function(req, res) { res.sendFile(__dirname + '/path/to/your/angular/public/index.html'); });
2. Double-Check Your <base> Tag
You already have <base href="/admin/" /> set up, which is correct—but make sure:
- It's placed inside the
<head>section of yourindex.html - The trailing slash (
/) is included (this ensures relative paths in templates resolve correctly)
3. Verify Route Configuration Details
A couple of quick checks to rule out other issues:
- Your state URLs (
'cats'and'dogs') are correct with the base href—they'll resolve to/admin/catsand/admin/dogs, which is what you want. - Your
templateUrlpaths ('/app/components/cats/cats.html') are absolute, so they should load fine as long as your server is serving the/appdirectory correctly. If you run into template loading errors on refresh, confirm the server can access these files.
Final Notes
Once you set up the server rewrite rules, refreshing the page should work as expected: the server sends index.html, Angular boots up, and UI-Router takes over to load the correct state based on the URL.
内容的提问来源于stack exchange,提问作者hypercube

