我有一个使用 ngRoute 模块的 Angular 应用程序以及 HTML5 模式 pushState 以获得更干净的 URL。
app.config(function($routeProvider, $locationProvider){
$locationProvider.html5Mode(true);
$routeProvider
//Route for home page
.when("/", {
templateUrl: "templates/main.html",
controller: "imageController",
})
//Route for about page
.when("/me", {
templateUrl: "templates/me.html",
controller: "imageController",
})
//404 error
.when("/404", {
template: "",
controller: "imageController",
title: "404 Error",
})
//Default route to /
.otherwise({
redirectTo: "/404",
});
});
我已经更改了我的 .htaccess 文件以重写尾随斜杠 ("/")。
RewriteEngine on
RewriteBase /
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Redirect urls without a trailing slash
RewriteRule ^(.*)/$ $1 [L,R=301]
# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]
这适用于一个尾部斜杠,例如"http://example.com/me/"更新为"http://example.com/me"并相应地进行路由。
但是,当有多个斜杠时,路由会中断,例如"http://example.com/me/foo"路由到不完整的页面,而不是重定向到"/404"。如何解决此问题,以便如果"/me/foo"路由不存在,它将被重定向到"/404"。
您的问题是$route在/me 之后没有寻找任何东西,因此它将其视为 404。
如果您希望参数遵循路径,请对路径执行此操作。
.when("/me/:params?", { // The ? allows for the parameter to be empty so /me and /me/foo will both return the correct route
templateUrl: "templates/me.html",
controller: "imageController",
})
如果你想在路由被调用后检索这些 routeParams,你需要做的就是在你的控制器或指令中使用$routeParams
,就像这样。
scope.myParam = $routeParam.params; //In the instince of the URL above your scope.myParams would set to foo
出了我的问题的解决方案。我在需要 Apache 应用重写规则的特定文件夹中使用了多个.htaccess
文件。
例如,要将所有内容路由到 http://example.com/me/,我在/me
文件夹中创建了一个单独的.htaccess
文件,并将RewriteBase
更改为/me/
。