angularjs路由跳转页面后刷新报404错误

文章允许转载,需注明来源:http://www.jb51.cc/article/p-dldgxwzc-ee.html

服务器环境: Nginx

angularjs自带路由功能,当通过路由跳转的新页面时,由于目录下并不存在该页面对应的静态文件,所以此时执行刷新页面,会报404的错误。进一步讲,原因是在刷新请求页面时,Nginx 等服务器会先于angularjs接管页面跳转,由于Nginx并没有 angularjs里的路由,因此会报错。所以解决方法就是让Nginx把路由转发的功能交回angularjs的ng-app。

Nginx服务器下的配置方法

项目路径 www/testng/dist/index.html

location /testng {
                        root www;
                        index index.html index.htm;
                        try_files $uri /testng/dist/index.html;
                   }

主要就是使用了Nginx的try_files规则:

try_files
语法: try_files file … uri 或 try_files file … = code
认值: 无
作用域: server location
Checks for the existence of files in order,and returns the first file that is found. A trailing slash indicates a directory - $uri /. In the event that no file is found,an internal redirect to the last parameter is invoked. Do note that only the last parameter causes an internal redirect,former ones just sets the internal URI pointer. The last parameter is the fallback URI and must exist,or else an internal error will be raised. Named locations can be used. Unlike with rewrite,$args are not automatically preserved if the fallback is not a named location. If you need args preserved,you must do so explicitly:

简单的说,try_files会依次尝试参数中的地址,直到找到为止,如果找不到,以最后一个地址为准。

参考:
nginx中的try_files指令解释
How to: Configure your server to work with html5Mode
nginx部署 angularjs时的rewrite问题

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...