Pregunta

I have been struggling with the same issue for a while now and I could not find an good answer yet. I'm using rack-rewrite to add some url rewrite rules to my app's middleware stack.

I have the following rule:

r301 %r{^/([^(docs|help|legal|login|account|apps)])(.+)/$}, '$1'

Which is not working properly or as I would expect it. I have tried one of my previous question's answer, but neither that works, it actually generates an event more weird behaviour (it redirects to an url without the domain name, just to the path).

What I am trying to do is:

  • if user requests http://example.com/ or http://example.com/random-path/ I need the rewrite rule to strip the slash, thus the examples would become http://example.com respectively http://example.com/random-path;
  • if the requested paths matches any of the paths in the list docs|help|legal|login|account|apps, do not strip the slash at the end of the path if exists, but add a slash if it's not there

I tried with two rules, one that ignores the listed paths above and strips slashes and one that adds the slash if it hits something from the list and the slash after the path is not there:

r301 %r{^/([^(docs|help|legal|login|account|apps)])(.+)/$}, '/$1'
r301 %r{^/([(docs|help|legal|login|account|apps)])(.+)/$}, '/$1/'

How could I write a rule that would do that, or two rules, because what I tried it did not work?

¿Fue útil?

Solución

You can do that like so:

r301 %r{^/((?!docs|help|legal|login|account|apps).+)/$}, '/$1'
r301 %r{^/((?=docs|help|legal|login|account|apps).+[^/])$}, '/$1/'

example 1

example 2

and some documentation on lookahead and lookbehind

EDIT: stray parentheses.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top