Reputation: 1738
I am in a situation where an user can create his blog in a subdomain.
Users will create blogs and enter the address he wants like say,
abcd.domain.com
Then my php code creates a directory called abcd
.
To view the blog user will type in abcd.domain.com
in his browser and I want a .htaccess
code which will rewrite the url and open the files inside the domain.com/abcd
But for the user the url in the browser should stay abcd.domain.com
Currently I am trying this code
RewriteCond %{HTTP_HOST} ^test\.domain\.com$
RewriteCond %{REQUEST_URI} !^test/
RewriteRule ^(.*)$ /test/$1 [L,QSA]
But this gives me 404 even though I have a file test.html
inside the test folder and trying to view that page.
Also in this situation I will have to manually make change to the .htaccess file for URL rewrite. What I want to know is if it is possible to have a wild card subdomain redirect to the respective directory.
Upvotes: 1
Views: 249
Reputation: 24478
Note that it takes more than a rewrite rule to have wildcard subdomains. Just fyi.
You need to have created a wildcard DNS record
for subdomains and also tell apache to use any subdomain request by having a ServerAlias
of *.domain.com
in the apache config.
Then try your rule this way and see if it works for you.
RewriteCond %{HTTP_HOST} ^((?!www).+)\.domain\.com$ [NC]
RewriteCond %1::%{REQUEST_URI} !^(.*?)::/\1/?
RewriteRule ^(.*)$ /%1/$1 [L,QSA]
Upvotes: 1
Reputation: 18671
You can use:
RewriteCond %{HTTP_HOST} ^test\.domain\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/test/
RewriteRule ^(.*)$ /test/$1 [L,QSA]
REQUEST_URI
with leading /
.
With wild card subdomain:
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} ^(.+)\.domain\.com$ [NC]
RewriteCond %{REQUEST_URI} !^/%1/
RewriteRule ^(.*)$ /%1/$1 [L,QSA]
Upvotes: 2