Home > Net >  Htaccess regex that redirects a particular pattern to the homepage
Htaccess regex that redirects a particular pattern to the homepage

Time:11-04

I'm trying to use a regex to redirect queries that contain /page/ and ?lang=xx or &lang=xx to the homepage.

This is what I've tried so far, the first part of the rule works but not the one with the ?lang= and &lang= after the first question mark.

RewriteRule ^page/([0-9] )/?(\?|&)lang=([a-z]{2})$ https://example.com [R=301,L]

Any help will be greatly appreciated.

CodePudding user response:

RewriteRule ^page/([0-9] )/?(\?|&)lang=([a-z]{2})$ https://example.com [R=301,L]

The RewriteRule directive matches against the URL-path only. To match the query string you need to match against the QUERY_STRING server variable in a preceding condition. For example:

RewriteCond %{QUERY_STRING} (^|&)lang=[a-z]{2}(&|$)
RewriteRule ^page/\d /?$ https://example.com/ [R=301,L]

You've not stated the actual URLs you are trying to match, so based on your rule, this will match URLs of the form /page/<number>/, where the trailing slash is optional. Plus the lang URL parameter must be present anywhere in the query string and the value of which must be two letters. If the lang URL parameter is present, but is empty or contains more than two letters then it won't match and no redirect occurs.

\d is a shorthand character class that is the same as [0-9]. The capturing subgroups that you had in your original rule are not required.

Test first with a 302 (temporary) redirect to avoid potential caching issues. Ensure your browser cache is cleared before testing.

  • Related