.htaccess rewrite rule to keep subdomains when redirecting to the same domain with a subpath

Last updated on 29/03/2020

A very specific use-case example

Given I have the following URLs:

  • one.cornel.co
  • one.cornel.co/my-uri
  • two.cornel.co/
  • two.cornel.co/my-uri

I want my URLs to keep the identical subdomain but the URL prefixed with /special if there is no any URL specified



RewriteCond %{HTTP_HOST} ^(one|two)\.cornel\.co$ [NC]
RewriteCond %{REQUEST_URI} !^/[^/]+.*?
RewriteRule ^(.*)$ /special [L,R=301] 


In case you want to apply the rule to any subdomain, replace (one|two)\. with (.*)

PS: A good resources to workout your use-case is mod_rewrite cheat sheet and the long answer here.