在AngularJS网站上刷新404页面?

时间:2013-07-28 20:26:29

标签: .htaccess angularjs github http-status-code-404 github-pages

每当我:

,我都会收到404页面的服务

1。)刷新Angularjs网站上的任何网页(根页除外)

2。)点击返回,从404页面转到根页面(根页面将是404)

这是我的.config()代码

'use strict';

angular.module('mmApp', ['ngResponsiveImages'])
  .config(function ($locationProvider, $routeProvider) {
    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix = '!';
    $routeProvider
      .when('/', {
        templateUrl: '/views/design.html',
        controller: 'MainCtrl'
      })
      .when('/about', {
        templateUrl: '/views/about.html',
        controller: 'MainCtrl'
      })
      .when('/contact', {
        templateUrl: '/views/contact.html',
        controller: 'MainCtrl'
      })     
      .otherwise({
        redirectTo: '/'
      });
  });

我遇到过类似的问题,但不太了解答案或如何实施。

AngularJS - Why when changing url address $routeProvider doesn't seem to work and I get a 404 error

接受的答案是设置Apache以重新配置到根的所有路径。我的网站是在Github Pages上。我的.htaccess repo中有一个gh-pages文件,但我不知道如何配置它以将所有路径发送到根目录。

答案说另外要考虑的是使用像<base>这样的<base href="/" />元素,但我会把它放在哪里?在我的index.html?如果是,那么在该文件的顶部或底部?另外,我会将href值保留为/吗?

4 个答案:

答案 0 :(得分:13)

我在这里遇到了一个解决方案:https://coderwall.com/p/kfomwa

这是短篇帖子:

  

angularjs提供了html5Mode,它使您的应用程序使用基于pushstate的URL而不是hashtags。但是,这需要服务器端支持,因为生成的URL也需要正确呈现。

     

这实际上适用于github页面的自定义404页面,但它仅适用于启用自定义域的页面。

     

首先,将index.html中的所有内容复制到404.html。然后,将其添加到您的应用中:

 angular.module('app', []).config(function($locationProvider) {
      $locationProvider.html5Mode(true);
    });
     

请注意,如果您使用的是角度1.1.5,请确保将html5Mode设置为正常工作。

根据这些建议,我能够让我的网站正常运行。现在,当我点击重新加载时,页面正确加载。

答案 1 :(得分:4)

更好的选择是将任何网址重定向到index.html:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ index.html

这不会在任何页面上引起404响应。

答案 2 :(得分:2)

Github页面仅提供静态文件。它不会在.htaccess中读取您对Apache的任何配置设置。

如果您想从Github页面运行AngularJS应用程序,则无法使用html5Mode

答案 3 :(得分:1)

我在Vagrant上使用Nginx运行我的angularjs应用程序。并面临类似的问题。 在使用任何网址重新加载浏览器时,它会给我一个404页面。

我在主js文件中启用了html5mode。启用html5Mode后,您的网址中将不再使用#字符。 #符号很有用,因为它不需要服务器端配置。没有#,网址看起来更好,但它也需要服务器端更改。

以下是一些更改:

  • nginx.conf文件夹中打开nginx配置文件(/etc/nginx/sites-enabled)(路径因您的nginx安装目录而异)。
  • 查找try_files $uri $uri/ =404;并将其替换为try_files $uri $uri/ /index.html;
  • 保存nginx配置文件
  • 重新启动nginx sudo service nginx restart

我尝试在执行上述更改后重新加载页面。它按预期工作。