eL-Prova eL-Prova - 24 days ago 14
PHP Question

Htaccess redirect without define hardcoded domainname

I find a lot lot lot questions about redirection with htaccess.
However it seems no one has the same "problem" as me.

What I want is redirect if a directory is accessed, it should redirect to the subdomain. So far its good and working. However, I dont want to change my htaccess all the time when a domainname is changed.

So I have:

RedirectMatch 301 ^/subdir/(.*)$ http://subdir.example.com/$1


But in my case I put my application on the domain example2.com, I have to change the name.
Is it possible to have something like this:

RedirectMatch 301 ^**(capture_hostname)**/subdir/(.*)$ http://subdir.**(put_hostname_here)**/$1


All "solutions" seems to work with defining the domainname in htaccess.
I work not enough with htaccess to solve this issue. Therefore we are together :)

Answer

You can do it with mod_rewrite rules and capture hostname from a RewriteCond:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^(subdir)(/.*)?$ http://$1.%1$2 [L,NC,R=301,NE]

%1 is the value being captured from RewriteCond directive, $1 is subdir and $2 is part after subdir/