Search code examples
.htaccesshttp-redirectsubdomain

htaccess to redirect subdomains to a different URL with the subdomain info


With .htaccess files I need to take any URL as long as it has a non-www subdomain and redirect it to a different structure:

test.example.com -> example.com/r/test

another.example.com/foo/bar -> example.com/r/another

sub.example.com/q -> example.com/r/sub

www.example.com -> www.example.com

I've gotten close, but I can't seem to get it right.


Solution

  • You can use the following rules in your htaccess :

    RewriteEngine On
    
    RewriteCond %{HTTP_HOST} ^((?!www).+)\.example\.com$ [NC]
    RewriteRule ^ /r/%1 [L]
    

    This should rewrite foobar.example.com to example.com/r/foobar . The redirection is internal meaning that your browser URL won't change . You can use R=301 in your rule if you are looking for an external 301 redirection of URLs.