How to redirect from pages without trailing slashes to pages with trailing slashes

纵饮孤独 提交于 2019-12-24 05:03:28

问题


I have sammy.js running in a knockout.js app. I'm currently trying to redirect routes that are missing the trailing slash (for example /#/stop/1/100032) I would like to redirect all such pages missing the trailing slash, to the page with the trailing slash.

To complicate things, I would also like to have an error page in the case that there is no such route.

function RoutesViewModel () {
    var self = this;

    self.router = Sammy(function () {
        this.get('/#/stop/:agency_id/:stop_id/', function () {
            app.page.state('bus');
            app.stop.setCurrentById(this.params['agency_id'], this.params['stop_id']);
            mixpanel.track('stop page load', {
                'route': '/#/stop/' + this.params['agency_id'] + '/' + this.params['stop_id'] + '/',
            });
        });
        this.get('/(.*[^\/])', function () {
            this.redirect('/',this.params['splat'],'/');
        });
    });

    self.router.error = function (message, error) {
        app.page.header("Unable to find your page");
        app.page.message("The page you've requested could not be found.<br /><a href=\"/\">Click here</a> to return to the main page.");
    }

    self.run = function () {
        self.router.run();
    }
}

Above is a selection of the routes I have so far. Unfortunately, when I go to the example url above, the page loads the error, instead of the correct /#/stop/1/100032/.

Any help would be greatly appreciated.


回答1:


I know this is an old question, but I encountered this issue as well.

According to http://sammyjs.org/docs/routes routes are regular expressions. So this worked for me:

this.get('#/foo/:id/?', function() {



回答2:


I had this same problem, and decided to fix it with a catch-all at the end of my Sammy set-up. My solution removes the trailing slash if there is one, but you could easily do the reverse, adding a slash on instead:

Sammy(function () {
    this.get('#', function () {
        // ...
    });
    this.notFound = function (method, path) {
        if (path[path.length - 1] === '/') {
            // remove trailing slash
            window.location = path.substring(0, path.length - 1);
        } else {
            // redirect to not found
        }
    }
});


来源:https://stackoverflow.com/questions/12877577/how-to-redirect-from-pages-without-trailing-slashes-to-pages-with-trailing-slash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!