Home > database >  How to rewrite number of specific url to subdomain via htaccess
How to rewrite number of specific url to subdomain via htaccess

Time:10-20

I have a main domain and many subdomains on it now i want to redirect main domain to its HTTPS and other domains to its subdomain for example:

  • main.com redirects to https://main.com
  • domain1.com redirects to domain1.main.com
  • domain2.com redirects to domain2.main.com

now i using this

RewriteEngine On
RewriteBase /

RewriteCond %{SERVER_PORT} 80 
RewriteCond %{HTTP_HOST} ^www.main.com [OR]
RewriteCond %{HTTP_HOST} ^main.com [NC]
RewriteRule ^(.*)$ https://www.main.com/$1 [R,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

this code redirect main.com only and other domains must check in index.php and redirect to specific subdomain, i want to perform whole work in htaccess.

CodePudding user response:

This probably is what you are looking for:

RewriteEngine On
RewriteBase /

RewriteCond %{SERVER_PORT} 80 
RewriteCond %{HTTP_HOST} ^(?:www\.)?main\.com
RewriteRule ^ https://www.main.com%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTP_HOST} !^(?:www\.)?main\.com
RewriteCond %{HTTP_HOST} ^(?:www\.)?([^.] )\.com
RewriteRule ^ https://%1.main.com%{REQUEST_URI} [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

It makes sense to start out using a R=302 temporary redirection at first and only change that to a R=301 permanent redirection once everything works as desired.

Obviously this requires that requests to those other domains are handled by the http host which implements this rule set. So you most likely want to define either host aliases for those domains or use a default virtual host inside your http server.

  • Related