How to redirect subdomain to domain with subdomain as parameter

.htaccessmod-rewriteredirectsubdomain

I would like to redirect my wildcard subdomain to my main domain using the subdomain as a GET parameter in the URL using .htaccess.

Example of what I would like to happen:

billy.example.com

redirects to

www.example.com/profile?user_name=billy

Here is the current rule I have put together based on other answers on this site:

RewriteCond %{HTTP_HOST} ^(.*).example.com
RewriteRule ^(.*)$ http://www.example.com/shop?user_name=%1 [R,L]

However, when the redirect happens I get the following URL with a "Redirect Loop" error:

www.example.com/profile?user_name=www

I've seen this answered a few different ways on this website but unfortunately none of them worked for me.

(I'm using PHP, and I have setup * as a subdomain in my hosting panel.)

Best Answer

Your redirect loop is happening because you are redirecting everything (even www.example.com). Maybe try something like:

RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
RewriteCond %{HTTP_HOST} ^([^\.]+)\.example\.com$ [NC]
RewriteRule ^/(.*)$ http://www.example.com/shop?user=%1 [L,R=301]

This should only fire when you're on something other than www.example.com.

Related Topic