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

文章允许转载,需注明来源:http://blog.csdn.net/feiniao8651/article/details/72898403

服务器环境: 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问题

你可能感兴趣的:(服务器配置)