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

前端之家收集整理的这篇文章主要介绍了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问题

原文链接:https://www.f2er.com/angularjs/147133.html

猜你在找的Angularjs相关文章