Home > Enterprise >  .htaccess rewrite domain and subdomain to directory and subdirectory
.htaccess rewrite domain and subdomain to directory and subdirectory

Time:12-23

I'm trying to use my .htaccess file to point domains/subdomains to directories/subdirectories without changing the url in the browser.

Examples of the incoming url and the directory it should point to:

  • domain1.com/* -> /domain1.com/www/*
  • foo.domain1.com/* -> /domain1.com/foo/*
  • bar.domain1.com/* -> /domain1.com/bar/*
  • domain2.com/* -> /domain2.com/www/*
  • foo.domain2.com/* -> /domain2.com/foo/*
  • bar.domain2.com/* -> /domain2.com/bar/*

Here's my current attempt that is continually appending the directory/subdirectory to the url:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^(?:([^.] )\.)?([^.] )\.([^.] )$ [NC]
RewriteCond %{REQUEST_URI} !^/%2\.%3/%1/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /%2.%3/%1/$1 [L,NE,P,QSA,R]

CodePudding user response:

Why so complicated? The following should satisfy all requirements you listed:

RewriteCond %{HTTP_HOST} ^([^.] )\.[^.] $
RewriteRule ^ /www%{REQUEST_URI} [L]

RewriteCond %{HTTP_HOST} ^([^.] )\.([^.] )\.[^.] $
RewriteRule ^ /%1%{REQUEST_URI} [L]

Have a try yourself at made with love

CodePudding user response:

It took a little work, but that to the help of the first response, I was able to get everything working eventually.

Here's my final solution to this issue:

## Turn the rewrite engine on to allow for url mapping to work
RewriteEngine on

## Don't require a trailing "/" for directories
DirectorySlash Off

## If subdomain was missing, redirect into the "www" subdirectory

# If no %{REQUEST_FILENAME} was provided, redirect to the "www" subdirectory
RewriteCond %{HTTP_HOST} ^([^.] )\.([^.] )$ [NC]
RewriteRule ^$ /%2.%3/www/ [END,NC]

# If a %{REQUEST_FILENAME} was provided, redirect to the directory/file in the "www" subdirectory
RewriteCond %{HTTP_HOST} ^([^.] )\.([^.] )$ [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /%2.%3/www/$1 [END,NC,QSA]

# If subdomain was given, redirect into the given subdirectory

# If no %{REQUEST_FILENAME} was provided, redirect to the given subdirectory
RewriteCond %{HTTP_HOST} ^([^.] )\.([^.] )\.([^.] )$ [NC]
RewriteRule ^$ /%2.%3/%1/ [END,NC]

# If a %{REQUEST_FILENAME} was provided, redirect to the directory/file in the given subdirectory
RewriteCond %{HTTP_HOST} ^([^.] )\.([^.] )\.([^.] )$ [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /%2.%3/%1/$1 [END,NC,QSA]
  • Related