I've used the following rules in my htaccess file in other applications to redirect users from a folder to a subdomain but load the content from that folder when accessing that subdomain.
# REWRITE SUBDOMAIN TO FOLDER
RewriteCond %{HTTP_HOST} ^admin\.cameron\.com$
RewriteRule !^admin/? admin%{REQUEST_URI} [NC,L]
# REWRITE FOLDER TO SUBDOMAIN
RewriteCond %{THE_REQUEST} \s/admin/([^\s]*) [NC]
RewriteRule ^ http://admin.cameron.com/%1 [R=301,L]
So if I go to: http://cameron.com/admin
I end up on http://admin.cameron.com/
But the content is loaded from http://cameron.com/admin
However this doesn't work for CakePHP 2.x because of its rewriting apparently...
In my htaccess file in /app/webroot
I have:
<IfModule mod_rewrite.c>
RewriteEngine On
# CAKEPHP RULES
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]
# REWRITE SUBDOMAIN TO FOLDER
RewriteCond %{HTTP_HOST} ^admin\.cameron\.com$
RewriteRule !^admin/? admin%{REQUEST_URI} [NC,L]
# REWRITE FOLDER TO SUBDOMAIN
RewriteCond %{THE_REQUEST} \s/admin/([^\s]*) [NC]
RewriteRule ^ http://admin.cameron.com/%1 [R=301,L]
</IfModule>
If I go to: http://cameron.com/admin
it just tries to load the AdminController and doesn't redirect you, and if I go to: http://admin.cameron.com/
I just get a 500 Internal Server Error.
Any ideas on how to get this working for CakePHP?
CakePHP and almost any other PHP framework parse $_SERVER['REQUEST_URI'] in order to route your request to particular controller
more info here: https://github.com/cakephp/cakephp/blob/2.6/lib/Cake/Network/CakeRequest.php#L230 ,
so you simply need to have the SAME request URI parameters for your redirect to get app working.
For your old location it was "/admin", for new location it should be the same, but you do not want to pass it, so it is better to change the task like this:
"When you go to admin.site.com you will be redirected to site.com/admin".
This can be done simply like this:
RewriteRule ^([^.]+)\.example\.com http://example.com/$1
It is not a working example of rule because you also need to rewrite subdomain's request URI to to get everything working and it depends on your requirements, but can be smth like this:
RewriteRule ^([^.]+)\.example\.com(.*) http://example.com/$1/$2
UPD: real example
$ cat app/webroot/.htaccess
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
RewriteCond %{HTTP_HOST} ^admin.example.com
RewriteRule ^(.*)$ http://example.com/admin/$1 [P,L,NC]
</IfModule>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With