Home > Net >  How to create htaccess redirect and pass on variables while matching regex?
How to create htaccess redirect and pass on variables while matching regex?

Time:12-01

I want to create redirects in .htaccess for all links that follow a certain url structure. However, the url structure has a variable in it, so I need to pass on the variable into the new url. The variable can be anything (string, number, query, etc), it just needs to be passed on into the new url. For example, /news-{VARIABLE}-2021 should become /news-{VARIABLE}-2022.

Following the .htaccess structure with regex, I created this, however the $ doesn't seem to pass on to the variable $1.

RewriteEngine On
Rewrite 301 /news-(.*)$-2021 /news-$1-2022

Following some other guides, I also tried to place the $ at the end of the url, or added a ^ before the first url (with and without the slash /). None of these seem to be working however. Could someone explain how I can create these new links with the variable in the middle?

CodePudding user response:

You cannot place $ (end anchor) in the middle of a regex pattern, also don't mix Rewrite directive (mod_alias Apache module) with RewriteEngine (mod_rewrite Apache module).

You may use:

RewriteEngine On

RewriteRule ^(news-. )-2021/?$ /$1-2022 [L,NC,NE,R=301]
  • Related