Regex folder redirection containing same name (creating loop)

Greg Cranston asked
wordpress .htaccess redirect mod-rewrite http-status-code-301
via

I’m trying to create a regex expression to redirect a folder and it’s contents, but am creating a redirect loop as the new folder starts with the same word. I’m actually putting this in the ‘Redirection’ Wordpress plugin, but hopefully should be same as mod_rewrite RewriteRule statements.

Intention:

FROM:   /photo  OR      /photo/   OR    /photo/anything/    
TO:     /photo-video    /photo-video/   /photo-video/anything/

Using:

/photo(.*) /photo-video$1     -> creates a redirect loop (keeps adding '-video')
/photo/(.*) /photo-video/$1   -> misses out the case without trailing /

I feel like after /photo I need to create a condition of: [ '/' followed by (.*) ] OR [ nothing ] (i.e. won’t match if further characters before a /).


Answer
via

The proper way to do this in regex:

FROM: ^/photo(/.*|$)
TO: /photo-video$1

/photo           -> /photo-video
/photo/          -> /photo-video/
/photo/anything  -> /photo-video/anything
/photo/anything/ -> /photo-video/anything/

Breaking this down for you:

^/photo(/.*|$)

  • Beginning of string ^
  • Followed by /photo
  • Followed by / and anything else; i.e., /.*
    • Or, followed by end of string (nothing) $
Share This
Posted in: