For a project I was trying to make dynamic sub domains for every user. I knew that it can be done by .htaccess mod_rewrite. But I didn’t know exactly how. Then I googled for solution and got a large number of tutorials. There I got some working tutorials too.
But the problem was, using those tutorials I can easily point a file like this:
RewriteEngine On RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L] RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com$ RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com$ RewriteRule ^(.*)$ user.php?uid=%1 [L]
And also like this:
<IfModule mod_rewrite.c> Options +FollowSymLinks Options +Indexes RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} !www.example.com$ [NC] RewriteCond %{REQUEST_URI} ^/$ RewriteCond %{HTTP_HOST} ^(www.)?([a-z0-9-_]+).example.com [NC] RewriteRule (.*) /welcome/user/%2 [R] </IfModule>
But these don’t work for Codeigniter. Second one work but change the browser URL. So this is a big problem. I tried removing [R]. But then no redirection.
Then I start reading mod_rewrite documentation. And finally realize that it is happening for a flag. You have to set flag [P]. It treat the URL as a proxy. So your URL in browser will not change. I am writing this article because when i searched there were not enough documentation to describe this problem simply.
Hope this will help you.
Final and Working Code:
<IfModule mod_rewrite.c> Options +FollowSymLinks Options +Indexes RewriteEngine On RewriteBase / RewriteCond %{HTTP_HOST} !www.example.com$ [NC] RewriteCond %{REQUEST_URI} ^/$ RewriteCond %{HTTP_HOST} ^(www.)?([a-z0-9-_]+).example.com [NC] RewriteRule (.*) /index.php/controller/function/%2 [P] RewriteCond $1 !^(index\.php|images|robots\.txt|css|js) RewriteRule ^(.*)$ /index.php/$1 [L] </IfModule>
Hi,
im trying to figure what “function” is refering to… Can you give me more details?
Thanks!
You have to place your controller and function name here “controller/function”
suppose u want to redirect to controller named test and a function in this controller named “test_function”. Then you have to do like this
RewriteRule (.*) /index.php/test/test_function/%2 [P]
in test_function method u’ll get the subdomain as parameter.
Thanks
Hi,
can you explain what “function” at line 10 is refering? A controller named function? Can you give me more info please?
Thanks!
The function in controller class.
Hello
I am trying to use your code but its not working for me
my controller name is welcome and function name is user
my url like http://sell4cell.com/welcome/test/nn
but i want it should be rewrite http://nn.sell4cell.com/welcome/test
Really works for CI !!!
Thanks very much!!!
Hmm. Wont work for me. I have a wildcard dns zone set for the domain. I’ve put the htaccess in place, but still nothing. I’m on hostgator. Not sure that would make any difference
Not Working for me too
Thanks. It works good for me.