1

I have looked through and tried many different suggestions all to no avail. please help!

I want to redirect all subdomains to main domains. I have pointed the DNS for wildcard subdomains to my IP with A zone and currently any subdomain entered will lead to 404. My eventual result would be that for any subdomain and their URLS, it will be redirected to the main domain. i.e.

blog.my-domain.com -> my-domain.com (yes my domain has a dash)

test.my-domain.com/testing -> my-domain.com

example.my-domain.com -> my-domain.com

my current .htaccess file is as below:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

# DO NOT REMOVE THIS LINE AND THE LINES BELOW SSL_REDIRECT:my-domain.com
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^my-domain.com$
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# DO NOT REMOVE THIS LINE AND THE LINES ABOVE SSL_REDIRECT:my-domain.com

I tried adding this piece of code at the bottom but didnt work

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.+)\.my\-domain\.com$ [NC]
RewriteRule (.*) https://my-domain.com%{REQUEST_URI} [L,R=301]

please help thanks!!

Chris
  • 147
  • 2
  • 17
  • Have you defined virtual host in your Apache configuration for common IP you wish to use for main domain and all sub domains? – Kishan Parekh Jun 15 '19 at 17:47

1 Answers1

4

1) Add this rule before line "# BEGIN WordPress"

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} !^my-domain.com$ [NC]
RewriteRule ^(.*)$ https://my-domain.com/$1 [R=301,L]

It's 1:1 rewrite example:

(http or https)://any-subdomain.my-domain.com/link <> https://my-domain.com/link

2) Another possibility is add only rule for subdomains, add it before line "# BEGIN WordPress"

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^(.*)\.my-domain\.com$ [NC]
RewriteRule ^(.*)$ https://my-domain.com/ [R=301,L]

It's rewrite all subdomains requests to my-domain.com, example:

(http or https)://any-subdomain.my-domain.com/link <> https://my-domain.com/

Check the option that you prefer more.

JarekBaran
  • 1,311
  • 2
  • 7
  • 12
  • Hi, Thanks for your answer but it is not working. Can i double confirm that we are able to redirect subdomains using main domain's htaccess file? – Chris Jun 10 '19 at 15:21
  • 1) totally works for me for a wildcard redirect for subdomain to main domain. Thanks! – Gray Ayer Oct 07 '21 at 00:31