简体   繁体   中英

Redirect URL when there are trailing slashes

I have an app which is build using NextJS. When it's in production, it allows trailing slashes but breaking a bunch of other stuff. It gives me the following error:

Failed to execute 'replaceState' on 'History': A history state object with URL 'https:' cannot be created in a document with origin ' https://myapp.com ' and URL ' https://myapp.com/// '. Error: Failed to execute 'replaceState' on 'History': A history state object with URL 'https:' cannot be created in a document with origin ' https://myapp.com ' and URL ' https://myapp.com/// '.

I would like to simply redirect to the correct address whenever there are trailing slashes.

So for example, user types: myapp.com/// , I would like to redirect them to myapp.com , using NextJS routing. Is this possible? How do I do this?

Your app shouldn't support this kind of trailing slashes in the first place. myapp.com/ is one thing, myapp.com/// is another thing.

AFAIK, Google also sees it that way, so if you allow multiple trailing slashes in your url Google will end up showing you a bunch of duplicates (as each url with an extra / delivers the same content as without it). If you're using NextJs, you care about SEO, most likely.

The correct solution is to always force a trailing slash on your urls. If you're running express you can use connect-slashes on production to always force the trailing slash.

Beware, as this will break your /static/ folder. You can fix this with the express static middleware: server.use(express.static('static')); .

If, however, you're insistent on allowing multiple slashes, I'd strongly recommend clearing them server-side and showing a single / . So myapp.com//// becomes myapp.com/ after going through your middleware.

I'd modify the connect-slashes repo mentioned before or create my own. A simple regex to catch repetitive / at the end of your url should do the trick. replace it with just one and you're good to go.

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