Search code examples
apache.htaccessurlhttp-redirectsubdomain

Redirecting folders to their corresponding subdomains


Trying to configure apache via .htaccess so any folder will be redirected to the corresponding subdomain:

Example:

Original URL: http://zipcode.is/ro/010011 redirects to: http://ro.zipcode.direct/010011

Moving the folder from zipcode.is/ro/010011 to a subdirectory on the new domain: ro.zipcode.direct/010011 (note that the domain is different as well). Now this is working but as soon as I change the country ISO code, it won't work any more e.g. zipcode.is/us/10128


Solution

  • RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteRule ^([a-zA-Z]+)/(\d+)$ http://$1.zipcode.direct/$2 [R=301,L]
    

    the above was the best and shortest solution (thanks Ruslan G.!), the first method by Alexey S. doesn't check types and was less elegant, left it in case someone wants to further tweak:

    RewriteEngine on
    
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteRule ^(.*)/(.*)$ http://$1.zipcode.direct/$2 [R=301,L] 
    
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteRule ^([^.]*)$ http://$1.zipcode.direct [R=301,L]