当您在 angularjs 中启用 html5 模式/推送状态模式时,这是您的服务器应该处理的常见情况。如果我正确理解了您的问题,则服务器会在您刷新页面时返回 404,否则如果从登录页面导航,则该页面将呈现正常。如果是这种情况,请告诉我:
- Angular 应用进入主屏幕,例如 your_domain/
- 导航到其他页面 - your_domain/somepage(在 hash bang 模式下将是 your_domain/#somepage)
- 刷新页面 -> 抛出 404
如果您面临的情况与上面给出的一样,那么会发生这种情况:
- 加载主页 -> angular 已引导并设置路由
- 导航到“somepage” -> 角度路由处理此问题并显示“somepage”
- 刷新页面 -> 请求到达服务器并请求 your_domain/somepage - 这在服务器中不可用
- 服务器返回 404
如何处理?
在 404 的情况下,是否将 Url 从服务器重写回 your_domain/。这将引导 Angular 应用程序,并且 Angular 路由将处理请求
更多细节在这里 - https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode
从上面的网站复制粘贴
Apache 重写
<VirtualHost *:80>
ServerName my-app
DocumentRoot /path/to/app
<Directory /path/to/app>
RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]
</Directory>
</VirtualHost>
Nginx 重写
server {
server_name my-app;
root /path/to/app;
location / {
try_files $uri $uri/ /index.html;
}
}
Azure IIS 重写
<system.webServer>
<rewrite>
<rules>
<rule name="Main Rule" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
</system.webServer>
快速重写
var express = require('express');
var app = express();
app.use('/js', express.static(__dirname + '/js'));
app.use('/dist', express.static(__dirname + '/../dist'));
app.use('/css', express.static(__dirname + '/css'));
app.use('/partials', express.static(__dirname + '/partials'));
app.all('/*', function(req, res, next) {
// Just send the index.html for other files to support HTML5Mode
res.sendFile('index.html', { root: __dirname });
});
app.listen(3006); //the port you want to use
ASP.Net C# 重写
在 Global.asax 中
private const string ROOT_DOCUMENT = "/default.aspx";
protected void Application_BeginRequest( Object sender, EventArgs e )
{
string url = Request.Url.LocalPath;
if ( !System.IO.File.Exists( Context.Server.MapPath( url ) ) )
Context.RewritePath( ROOT_DOCUMENT );
}