【问题标题】:Angular Route with multiple slashes override folder path带有多个斜杠的 Angular Route 覆盖文件夹路径
【发布时间】:2016-10-11 22:36:49
【问题描述】:

我有一个 Angular 应用程序,它使用 ngRoute 模块和 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”。

【问题讨论】:

    标签: angularjs .htaccess routing angularjs-ng-route trailing-slash


    【解决方案1】:

    您的问题是 $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
    

    【讨论】:

    • 当我这样做时,我的 '/me' 路线将不起作用。我的问题不是针对“/我”,而是针对任何多个斜杠的一般问题。例如我希望将“example.com/blah/blah”路由到“/404”。有什么想法吗?
    • 是的,$routeParams 应该适用于所有带有多个斜杠的路由。我还编辑了我的回复,以展示如何在没有任何参数的情况下使其工作。 /me 和 /me/foo 都应该这样工作。
    • 我试过你的建议,但还是不行。可能是因为我启用了 HTML5 pushState?也许我需要调整我的 .htaccess 重写?任何其他想法将不胜感激。谢谢。
    【解决方案2】:

    我找到了解决问题的方法。我在需要 Apache 应用重写规则的特定文件夹中使用了多个 .htaccess 文件。

    例如要将所有内容路由到http://example.com/me/,我在/me 文件夹中创建了一个单独的.htaccess 文件并将RewriteBase 更改为/me/

    【讨论】:

      猜你喜欢
      • 2012-11-16
      • 1970-01-01
      • 2018-10-01
      • 2015-03-24
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多