简体   繁体   中英

Node.js redirect with/without trailing slash

I have a javascript that does different things depending on the URL. for that to work, i need to have consistent URIs.

for example, i need users to always be on www.site.com/users/bob/ instead of www.site.com/users/bob

node unfortunately doesn't support that, as it seems.

i tried redirecting with

router.get('/:user', function(req, res) {
    res.redirect('/users/' + req.params.user' + '/');
});

but it just results in a redirect loop, as the URL with and without slash seem to be treated as the same.

how can i do this? thanks!

edit:

i want to route from WITHOUT slash to WITH slash. the answers in the other question address the other way around. i can't .substr(-1) my URLs

In case someone else is looking for a quick zero dependency solution, this worked fine for me:

app.get('/:page', function(req, res){
  // Redirect if no slash at the end
  if (!req.url.endsWith('/')) {
    res.redirect(301, req.url + '/')
  }

  // Normal response goes here
});

You can get this by using third-party library which is called express-slash . All you need to do is,

First, install the library

$ npm install express-slash

And, add these to your app.js.

var slash   = require('express-slash');

app.use(slash()); // set slash middleware

Then, this is your router.

router.get('/:user/', function(req, res) {
    // do your stuff
});

Hope it will be useful for you.

Set this use after the 'express.static' use and before other use methods.

This code removes the slash from the end of path if it exists, and redirects to the new URL.

If you what to add a slash you can change it so that it adds a slash if the original path doesn't have one.

app.use((req, res, next) => {
    let url = parseURL(req.url),
        pathname = url.pathname,
        search = url.search || '',
        hasSlash = pathname.charAt(pathname.length - 1) === '/';

    if (hasSlash && pathname !== '/') {
        // remove slash
        pathname = pathname.slice(0, -1);
        // redirect to truest url
        res.redirect(301, pathname + search);
    } else {
        return next();
    }
});

I'm adding this answer as a full solution that redirects non-slash routes to end with a slash.

Firstly, enable a strict router (v4+) to disable the auto normalisation.

express.Router({strict: true});

Then start your router with a catch-all route which detects if it doesn't end with a slash - and in this case also omits anything with a (.) - so images etc aren't caught.

var url = require('url');
router.all(/^[^.]*[^\/]$/, function(req, res) {
    let u = url.parse(req.originalUrl);
    return res.redirect(301, u.pathname + '/' + (u.search || ''));
});

This works with query string parameters etc.

You could try jncraton's answer , but only append slashes to directories..

const path = require('path')

app.get('/*', function(req, res) {
    if (!req.url.endsWith('/') && !path.extname(req.url)) {
        res.redirect(301, req.url + '/')
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM