Redirect subdomain to CakePHP action

♀尐吖头ヾ 提交于 2020-01-03 20:58:08

问题


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.comhttp://myserver.com/m/mysite/
  • http://mysite.myserver.com/homehttp://myserver.com/m/mysite/home
  • http://mysite.myserver.com/foo/bar?baz=truehttp://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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!