Yurii Kovalchuk
Yurii Kovalchuk

Reputation: 101

Apache Rewrite Rules for specific cases

I have a .htaccess file and a couple of redirect rule.

For example:

RewriteRule ^blog/migrations/?$ / [R=301,L,NE]
RewriteRule ^blog/digital/?$ / [R=301,L,NE]

Basically, all my blog urls have been removed but i found redirects rule for every single blog url to redirect to main page. But i want this to be in one rule, something like this:

RewriteRule ^blog/{anyUrl}/?$ / [R=301,L,NE]

Also i have strange redirects, such as:

RewriteRule ^2/?$ / [R=301,L,NE]
RewriteRule ^3/?$ / [R=301,L,NE]
RewriteRule ^4/?$ / [R=301,L,NE]
RewriteRule ^5/?$ / [R=301,L,NE]
RewriteRule ^6/?$ / [R=301,L,NE]

And i want them to be one rule, for example:

RewriteRule ^{[2-6]}/?$ / [R=301,L,NE]

Can anyone help with those rule, i am not really good at regexps.

//Edited

Also i have a rule that redirects urls with query strings:

RewriteCond %{QUERY_STRING} .
RewriteRule ^(.*)/?$ /$1 [QSD,R=301,L]

But this rule removes all query strings. How can i exclude from the rule specific query strings that starts with utm_?

And how can i get the domain name? I have my website on two different domains. For example:

RewriteRule ^posts/? https://{domain}/somewhere

Upvotes: 1

Views: 218

Answers (1)

anubhava
anubhava

Reputation: 784908

You can combine all those rules into one rule using regex alternation:

RewriteRule ^(blog/|[2-6]/?$) https://%{HTTP_HOST}/ [R=301,L,NC]

This pattern ^(blog/|[2-6]/?$) will match start position and then either blog/ or [2-6] followed by optional / and end position.


For the other query string rule you can use:

RewriteCond %{QUERY_STRING} .
RewriteCond %{QUERY_STRING} !(^|&)utm_ [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [QSD,R=301,L,NE]

RewriteRule ^posts/? https://{domain}/somewhere

You don't need to use https://%{HTTP_HOST} here in redirect rules to make it same domain as in the request, so make it:

RewriteRule ^posts/? https://%{HTTP_HOST}/somewhere [L,R]

Upvotes: 2

Related Questions