Skip to content
Advertisement

How to remove trailing slash in react-router URLs

I start to use react-router in my application and I am noting that when it has a trailing slash at end of URL (/url/) it does not work. I searched more about it, read all documentation and react-router issues and tried to use <Redirect from='/*/' to="/*" />, however it was not a good solution, cause it did not work too. So, reading more I found out a suggestion to insert /?at end of URL, but it still not worked.

The code of routes.js:

JavaScript

The code of index.js:

JavaScript

Searching more, I found a guy who made a function to force trailing slash at URLs and I resolved to make the opposite of that, forcing to not have it.

Update routes.js code with function No trailing slash function:

JavaScript

And again this did not work! I need to make this URLs more friendly as possible and I would like that URLs do not have any trailing slash at the end. Any suggestion how can I make this? And why Redirect did not work in this case?

Advertisement

Answer

I found a good option to make this redirect. Below is the code which I am using:

JavaScript

The explanation is basicly it:

  1. In this function, I verify if the URL is grand then one and if it has a trailing slash.
  2. If true, I get this URL without trailing slash and make a 301 redirect to this page without the trailing slash.
  3. Else, I jump to next method to send a value.
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement