Search code examples
regex.htaccessmod-rewrite

Replace part of the URL and add two zeros in string with htaccess


Can anyone help me with this regular expression so I can replace:

This URL:

mydomain.com/artigos/8170-comooool

To:

mydomain.com/blog/817000-comooool

This is:

1: Replace the word `artigos` by `blog`
2: Add two zeros to the 4 digit number after the slash

I tried:

RewriteRule ^artigos(\d{4}-.*) /blog/$1 [R=301,L]

but nothing seems to work.


Solution

  • You can add this redirect rule just below RewriteEngine On line:

    RewriteEngine On
    
    RewriteRule ^artigos/(\d+)(-.*)$ /blog/$100$2 [L,R=301,NE,NC]
    

    We have to use 2 separate capture groups: 1st to capture all digits after /artigos/ and 2nd to capture all text beyond that.