How to redirect some subdomain pages to another page htaccess

Viewed 70

I need to redirect a few (not all) subdomain pages to another address in .htaccess:

How can I redirect the following:

spb.example.com/blog/
ekb.example.com/blog/
spb.example.com/projects/
ekb.example.com/projects/

to

example.com/blog/
example.com/projects/

I've tried:

    RewriteCond %{REQUEST_URI} ^spb.example.com/blog/$
    RewriteRule ^.*$ https://example.com/blog/? [R=301,L]

But it isn't working.

1 Answers
RewriteCond %{REQUEST_URI} ^spb.mytestsite.com/blog/$
RewriteRule ^.*$ https://mytestsite.com/blog/? [R=301,L]

The REQUEST_URI server variable contains the URL-path only. It does not contain the requested hostname (which is present in the HTTP_HOST server variable).

For example:

# Redirect "spb.example.com/blog/" to "example.com/blog/"
RewriteCond %{HTTP_HOST} ^spb\.example\.com [NC]
RewriteRule ^blog/$ https://example.com/blog/ [R=301,L]

However, you can do all 4 redirects in a single rule by using a more flexible regex and backreferences.

For example:

RewriteCond %{HTTP_HOST} ^(?:spb|ekb)\.example\.com [NC]
RewriteRule ^(blog|projects)/$ https://example.com/$1/ [R=301,L]

The $1 backreference contains either blog or projects from the requested URL-path (captured in the RewriteRule pattern).

NB: Test first with 302 (temporary) redirects to avoid potential caching issues.


UPDATE:

How can I redirect all blog articles from subdomains the same rules For example: from spb.example.com/blog/my-blog-article-1/ ekb.example.com/blog/my-blog-article-1/ to example.com/blog/my-blog-article-1/

You could do it like this by adding a second capturing group to the existing rule above:

RewriteCond %{HTTP_HOST} ^(?:spb|ekb)\.example\.com [NC]
RewriteRule ^(blog|projects)/(.*) https://example.com/$1/$2 [R=301,L]
Related