Search code examples
regexapachemod-rewrite

mod_ewrite + regex to append 0 to query string parameters


I have urls like this one...

https://localhost/index.php?com=liste-cat-lieux&t=41&l=6088

that i need to rewrite like this :

https://localhost/index.php?com=liste-cat-lieux&t=41&l=06088

I tried to append a leading 0

RewriteCond %{QUERY_STRING} ^(com=liste-cat-lieux&t=\d{2,3}&l=)(\d{4})$
RewriteRule ^index\.php /index?%10%2 [R=301,L]

It seemed to work fine when i tested it with tools like https://htaccess.madewithlove.com/, but it does not actually works in htaccess or apache


Solution

  • Your redirect rule appears correct but there is one problem. It doesn't check for existing leading zero this resulting in 0123 to 00123 and so on.

    I suggest you keep your redirect rule to this:

    RewriteCond %{QUERY_STRING} ^(com=liste-cat-lieux&t=\d{2,3}&l=)([1-9]\d{3})$ [NC]
    RewriteRule ^index\.php /$0?%10%2 [R=301,L,NC,NE]
    

    Here pattern [1-9]\d* matches parameter value l that starts with digits 1 to 9 followed by 0 or more digits.

    Also note use of /$0 in redirect URL that keeps same matched URI from RewriteRule which is /index.php.