F
F
Ferris2016-08-25 19:25:53
Regular Expressions
Ferris, 2016-08-25 19:25:53

How to make a redirect in .htaccess from several domains and subdomains to the corresponding domain/subdomains?

There was a need for a rather non-standard (for me) 301 domain redirect in .htaccess. In the case when there is a redirect from several domains (for example, domain1.ru, sub1.domain2.ru, sub2.domain1.ru) to a specific domain.ru domain while saving the address of the required page, I use the following code:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} !^domain\.ru$ [NC]
  RewriteRule ^(.*)$ http://domain.ru/$1 [L,R=301]
</IfModule>

But now I need to redirect:
sub1.domain1.ru to sub1. domain.ru
sub1.domain2.ru to sub1. domain.ru
sub3.domain4.ru to sub3. domain.ru
sub1.domain1.ru/section/index.php?test=test on sub1. domain.ru /section/index.php?test=test
and so on...
Speaking in Russian, I need to take a subdomain (if any) and transfer it to the same subdomain but within the main domain, and if there is no subdomain, then simply redirect to the main subdomain, keeping the page address after the domain/subdomain if a specific page was requested.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Ferris, 2016-08-26
@Ferris

I read about regular expressions in htaccess and came to this solution, maybe someone else will come in handy:

RewriteCond %{HTTP_HOST} !^domain.ru$|^(.*\.)domain\.ru$
RewriteCond %{HTTP_HOST} ^(.*\.)?(.*\.).*\..*$|^(.*).(.*)$
RewriteRule ^(.*)$ http://%2domain\.ru/$1 [L,R=301]

That is, all domains and subdomains not related to domain.ru will be redirected. Subdomains will be redirected to the corresponding subdomain of domain.ru, and second-level domains to the main one - domain.ru. The address of the requested page is also transmitted.

V
Vitaliy Orlov, 2016-08-26
@orlov0562

Something like this (didn't check)

RewriteCond %{HTTP_HOST} !([^\.]+)\.domain\.ru$
RewriteRule ^(.*)$ http://%1.domain.ru/$1 [R=301,L]

The point is that you use subdomain capture in RewriteCond, then what you captured can be output through %1 - %9

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question