Home > OS >  Url won't redirect using htaccess
Url won't redirect using htaccess

Time:12-25

i have a issue on the website im working on, i have 2 urls, url1

https://www.fakeurl/fr/histoires-d-art/interview-peintre-anne-baudequin

and url2

https://www.fakeurl/fr/module/_edito/EditoContent?slug=interview-peintre-anne-baudequin

Both url display the same content but i want to redirect url2 to url1 using htaccess, the code i wrote in in htaccess is not working and i dont understand why. This is it

redirect 301 /fr/module/_edito/EditoContent?slug=interview-peintre-anne-baudequin https://www.fakeurl/fr/histoires-d-art/interview-peintre-anne-baudequin

CodePudding user response:

I finally figured it out by myself, i had to change my code to this for it to work.

RewriteCond %{THE_REQUEST} ^(GET|POST)\ /fr/module/_edito/EditoContent\?slug=interview-peintre-anne-baudequin\ HTTP
RewriteRule ^ /fr/histoires-d-art/interview-peintre-anne-baudequin? [L,R=301]

CodePudding user response:

The mod_alias Redirect directive matches against the URL-path only, not the question string, so the above does not match the requested URL.

You need to use mod_rewrite with an additional condition that matches against the QUERY_STRING server variable (or THE_REQUEST). However, you also need to be careful of redirect loops since I assume you are also using a front-controller (that internally rewrites URL1).

Try the following instead, at the top of your .htaccess file:

# Redirect URL2 to URL1
RewriteCond %{THE_REQUEST} ^[A-Z]{3,7}\s/fr/module/_edito/EditoContent\?slug=interview-peintre-anne-baudequin\sHTTP [NC]
RewriteRule ^ /fr/histoires-d-art/interview-peintre-anne-baudequin [QSD,R=301,L]

THE_REQUEST contains the first line of the request headers and does not change when the request is internally rewritten.

The QSD flag is necessary to remove the original query string from the redirect response.

Test first with a 302 (temporary) redirect to avoid potential caching issues.

UPDATE: Fixed regex to backslash-escape the literal ? and added slash prefix to the RewriteRule substitution string.

  • Related