AngularJS:404页刷新,清洁URL,使用$ locationProvider.html5mode



我正在尝试使用$ locationprovider.html5mode(true)来解决问题。刷新页面时。

它在URL中修复了此localhost/#/home哈希,但是当我刷新页面时,它显示了404。

我正在使用nginx local

运行angularjs v1.0.7。最新版本显然不起作用。

标题

<base href="/">

Angular

var app = angular.module('myApp', []);
app.config(function($routeProvider, $locationProvider) {
      $routeProvider
      .when('/', {
        templateUrl: 'home.html',
        title: 'home'
      })
      .when('/about', {
        templateUrl: 'about.html',
        title: 'about'
      })
      .when('/contact', {
        templateUrl: 'contact.html',
        title: 'contact'
      })
      .otherwise({
        redirectTo: '/'
      });
      $locationProvider.html5Mode(true);
    });

当您使用html5模式时,链接从http://example.com/#about到http://example.com/about,但是有一件事,为什么您收到404-什么 - 什么服务器端解决方案您使用吗?由于您的后端而不是由AngularJS路由器本身返回404页面加载角度应用程序。例如,在Laravel中,想象您有这样的网站root路线,并且您的Angular App代码在Home.blade.php

    Route::get('/',function(){ return view('home');});

因此,您需要创建指向同一视图的相同路由以加载带有标记的Angular JS应用程序,然后您的Angular路由器将根据路由视图正确向您显示所需的模板。

   Route::get('/about',function(){ return view('home');});
   Route::get('/contact',function(){ return view('home');});

如果您使用不同的服务器端框架或解决方案,希望您对直接访问时需要做的解决方案有什么主要了解 - 只需在服务器端设置相同的路由,指向主页上加载Angular JS应用程序即可。 如果您不使用任何服务器端框架,则需要使用nginx使用静态HTML文件,则需要设置/contacts /about位置以指向您的文档root index.html,其中包含您的Angular App。

用于消除样本

location / {
    root   /srv/www/example.com/public_html;
    index  index.html index.htm;
}
location /about/ {
    root   /srv/www/example.com/public_html;
    index  index.html index.htm;
}
location /contacts/ {
    root   /srv/www/example.com/public_html;
    index  index.html index.htm;
}

最新更新