I'm trying to redirect all my folders (using a wildcard) to their subdomain. For example:
www.mywebsite.com/folder1 to folder1.mywebsite.com/
www.mywebsite.com/folder2 to folder2.mywebsite.com/
www.mywebsite.com/folder3 to folder3.mywebsite.com/
Now without writing a rule for each one of them, is there a way to redirect them all to their respective subdomain?
I tried:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.mywebsite\.com$
RewriteCond %{HTTP_HOST} ^(\w+)\.mywebsite\.com$
RewriteRule ^(.*)$ /%1/$1 [QSA]
But it gives me an internal error 500
You need to keep the rules from looping, use a condition to first check if the /%1/$1
actually exists, or that the URI doesn't already start with %1
So:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.mywebsite\.com$
RewriteCond %{HTTP_HOST} ^(\w+)\.mywebsite\.com$
RewriteCond %{DOCUMENT_ROOT}/%1%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}/%1%{REQUEST_URI} -d
RewriteRule ^(.*)$ /%1/$1 [QSA]
Or:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.mywebsite\.com$
RewriteCond %{HTTP_HOST} ^(\w+)\.mywebsite\.com$
RewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\1
RewriteRule ^(.*)$ /%1/$1 [QSA]
The !^/([^/]+)/([^:]*):\1
expression groups the first folder in the URI, and backreferences it with \1
. If those are equal, then the first folder in the URI is %1
which is backreferenced to the previous match (\w+)
.