angularjs routeprovider,html5mode和htaccess无法正常工作

时间:2017-11-05 23:46:50

标签: angularjs apache .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 / 时,网址会得到妥善处理。单击导航也可以正常工作。但是,如果我尝试在任何路由链接上刷新页面,或者尝试直接从地址栏访问它们,我会得到 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.

3 个答案:

答案 0 :(得分:1)

很久以前我遇到了类似的问题,有几件需要检查。

的index.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);
  ...
});

答案 1 :(得分:1)

看起来Apache正在对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]

这将使它跳过文件并在angular请求文件时前往index.html。

答案 2 :(得分:0)

原来这解决了问题

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