rack-rewrite icon indicating copy to clipboard operation
rack-rewrite copied to clipboard

Removing extra slashes in end of URL

Open nik-holo opened this issue 11 years ago • 6 comments
trafficstars

Not sure if it's ok to ask you about it here, but I hope you can help me.

I wanted to create redirect from "domain.com//////" to "domain.com/"

Is it possible?

Think it's gonna be helpful for other users if that is possible, so maybe you could include it in documentation.

nik-holo avatar Oct 29 '14 22:10 nik-holo

tracking, how did you solve this? I am also looking for a way to enforce trailing slashes.

chrishough avatar Jan 17 '16 23:01 chrishough

This is a very old issue, but in case it helps anyone:

use Rack::Rewrite do
  # remove trailing slashes
  moved_permanently %r{(/.*)/(\?.*)?$}, '$1$2'
end

It retains query strings after the trailing slash. You could make it /+ to handle domain.com//////

granth avatar Jul 25 '17 15:07 granth

Thank you @granth

chrishough avatar Jul 26 '17 06:07 chrishough

@granth Thank you for the solution. Do you know how to covert localhost:3000/en/articles///ads/// to localhost:3000/en/articles/ads ?

IvanDreamer avatar Oct 11 '17 11:10 IvanDreamer

@IvanDreamer I haven't used it, but you can pass a proc as an argument and gsub all the slashes there. See https://github.com/jtrupiano/rack-rewrite#arbitrary-rewriting

something like:

moved_permanently %r{(.*)}, ->(match, env) { match.to_s.gsub %r{//+}, "/" }

That matches every path and replaces each set of multiples slashes with a single slash.

granth avatar Oct 11 '17 17:10 granth

@granth Thank you for the response. Unfortunately it gives me "Too many redirects" 👎

IvanDreamer avatar Oct 12 '17 09:10 IvanDreamer