问题
Background
I have a CakePHP application that lives in /m/
. I want to write a root-level .htaccess
file which will redirect "subdomains" for the site as parameters to actions.
For example: I want to write a rewrite rule which will result in redirects like this -
http://mysite.myserver.com
→http://myserver.com/m/mysite/
http://mysite.myserver.com/home
→http://myserver.com/m/mysite/home
http://mysite.myserver.com/foo/bar?baz=true
→http://myserver.com/m/mysite/foo/bar?baz=true
Ideally, this redirect should be invisible to users (I don't want to use a 301, because I don't want to change the URL).
Here's my current attempt:
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.*)\.myserver\.com$ [NC]
RewriteRule ^(.*)$ http://myserver.com/m/%1/$1 [L]
</IfModule>
As far as I can tell, the main issue is with $_SERVER['REQUEST_URI']
:
- If I browse to
http://myserver.com/m/mysite/home
directly,$_SERVER['REQUEST_URI'] = /m/mysite/home
. - If I browse to
http://mysite.myserver.com/home
using the.htaccess
file above,$_SERVER['REQUEST_URI'] = /home
.
The Issue
Because of the issues with $_SERVER['REQUEST_URI']
, my routes aren't parsing correctly: it's trying to take the user to /home
rather than /m/mysite/home
as desired.
How can I change my rewrite rule to make this work properly? Is there another way to accomplish this?
回答1:
What you're asking (change the domain name in URL but don't let browser see URL change) is not achievable under normal scenario. However to make it possible you have enable mod_proxy
in your Apache and restart it. Once that is done use following code in your site root .htaccess:
RewriteCond %{HTTP_HOST} ^([^.]+)\.myserver\.com$ [NC]
RewriteRule !^m/ http://myserver.com/m/sites/%1%{REQUEST_URI} [NC,L,P]
来源:https://stackoverflow.com/questions/10438577/redirect-subdomain-to-cakephp-action