AngularJS RouteProvider、HTML5Mode 和 HTaccess 不起作用



我有一个启用了路由器和html5mode的单页应用程序

/account/
->index.html

路由器如下所示:

app.config(function($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true);
    $routeProvider
    .when('/account', {
        templateUrl: 'account/views/welcome.html',
    }) //works
    .when('/account/emails', {
        templateUrl: 'account/views/email.html', 
        controller: 'emailController'
    }) //404 error
    .when('/account/wallet', {
        templateUrl: 'account/views/wallet.html',
    }) //404 error
    .when('/account/settings', {
        templateUrl: 'account/views/settings.html',
        controller: 'settingsController'
    }) //404 error
    .when('/account/logout', {
        templateUrl: 'account/views/logout.html',
    }) //404 error
});

现在我还有一个 .htaccess 文件

/account/
->.htaccess

htaccess如下所示:

RewriteEngine On  
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]  
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d  
RewriteRule ^ - [L]
# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html  

正如预期的那样,当我转到//localhost/account/index.html//localhost/account/ 时,URL 得到了正确处理。单击导航也可以正常工作。但是,如果我尝试在任何路由链接上刷新页面,或者尝试直接从地址栏访问它们,我会得到 Apache2 Ubuntu 默认页面

不确定我在这里做错了什么,因为这似乎很简单?

另外,如果我将RewriteRule ^ /index.html更改为RewriteRule ^ /account/index.html而不是获取默认的Apache页面,则得到404:

Not Found
The requested URL /account/index.html was not found on this server.

我前段时间遇到了类似的问题,有一些部分需要检查。

索引.html

index.html文件的<head> 中,确保已设置基本 href:

<head>
  <base href="/">
  ...
</head>

.htaccess

你的.htaccess文件看起来基本上就像我写它时的样子。这是我使用的(重写可能很草率,但它对我有用!

# Enable URL rewriting/redirecting
RewriteEngine On 
RewriteBase /
# if requested filename is not a file that exists
RewriteCond %{REQUEST_FILENAME} !-f
# AND if requested filename is not a directory that exists
RewriteCond %{REQUEST_FILENAME} !-d
# THEN rewrite the URL to be /#/PREVIOUS_URL
RewriteRule ^(.*)$ /#/$1 [L]

AngularJS 路由器配置

您已经将html5Mode设置为 true,如代码所示:

app.config(function($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true);
  ...
});

看起来 Apache 正在对 angular 用于其路由的 URL 中的 # 进行吠叫。你需要这样的东西:

RewriteEngine on
# If an existing asset or directory is requested go to it as it is
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
# If the requested resource doesn't exist, use index.html
RewriteRule ^(.*) /index.html [NC,L]

这将使它跳过文件并前往索引.html当角度请求文件时。

事实证明,这解决了问题

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.html
</IfModule>

最新更新