A
A
Almaz Kalimullin2021-02-06 15:22:16
Regular Expressions
Almaz Kalimullin, 2021-02-06 15:22:16

.htaccess: How to use %N backreferences received in RewriteCond in other conditions?

Good afternoon!
I want to set it up so that every year all links with the old year are automatically redirected to the current year: https://site.com/folder/2020-february/ --->. https://site.com/folder/2021-february/

As done now:

RewriteCond %{REQUEST_URI} ^(.*)/2020(.*)$ [OR]
RewriteCond %{REQUEST_URI} ^(.*)/2019(.*)$ [OR]
RewriteCond %{REQUEST_URI} ^(.*)/2018(.*)$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%1/2021%2 [R=301,L]
#То есть каждый год приходится править условия


I want everything to be automatic:
RewriteCond %{REQUEST_URI} ^(.*)/(2[0-9]{3})(.*)$
RewriteCond %{TIME_YEAR} >%2
RewriteRule ^(.*)$ https://%{HTTP_HOST}%1/%2%3 [R=301,L]

But that doesn't work. I guess that the problem is in the second line ... I don’t know where to dig further.
Please tell me how to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dodo512, 2021-02-06
@muslim_nk

If there is a condition to check not strictly more, but simply a mismatch between %{TIME_YEAR} and %2

RewriteCond %{REQUEST_URI}  ^(.*)/(2\d{3})(-.*)$
RewriteCond %{TIME_YEAR}_%2 !^(\d+)_\1$
RewriteRule ^ https://%{HTTP_HOST}%1/%{TIME_YEAR}%3 [R=301,L]

Apache >=2.4 has expr and the condition can be checked like this%{TIME_YEAR} -gt $2
RewriteCond expr "%{REQUEST_URI} =~ m#^(.*)/(2[0-9]{3})(-.*)$# && %{TIME_YEAR} -gt $2"
RewriteRule ^ https://%{HTTP_HOST}%1/%{TIME_YEAR}%3 [R=301,L]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question