Search code examples
apache.htaccessmod-rewrite

htaccess RewriteRule redirect regex


I am trying to redirect url requests from http://www.xyz.com.au/lid/cid_855_1404172

To

http://www.xyz.com.au/lid/1404172

My regex matches the numbers after the last underscore but the final url is still appending the part I’m trying to omit

RewriteRule ([^_]+)$ /lid/$1

The result is:

http://www.xyz.com.au/lid/cid_855_/lid/1404172

What have I done wrong?


Solution

  • To be able to match and replace parts, you need to match all parts of the URI not a partial match.

    You may use this redirect rule:

    RewriteRule ^(.+/)?[^/]*_([^_]+)/?$ /$1$2 [L,R=301,NE]
    

    Details of the regex used:

    • ^: Start
    • (.+/)?: Match 1+ of any char followed by a /in capture group #1
    • [^/]*: Match 0 or more of any char that are not / (longest possible match; greedy)
    • _: Match a _
    • ([^_]+): Match 1+ of any char that are not _ in capture group #2
    • /?$: Match optional / and end anchor