手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 注册 | 登陆
浏览模式: 标准 | 列表2010年12月9日的文章

Yii 一行代码,为模块绑定子域名

我在dongbeta的网站上看到了这个东西,突然觉得原来子域名真的很简单,原来我还在想,如何绑定一些子域名的事情呢。

看一下原文吧,然后说明一下,官方的手册中其实已经有类似的介绍了,只是目前这一部分还是英文版的,这可能和这个功能是最新刚加入的关吧。。来源网址为:http://dongbeta.com/view/655

--start--

Yii强大的路由功能配置相当灵活,特别是增加了参数主机名路由功能之后更是可以灵活控制域名。感觉每一次提出一个提议,Yii的开发者qiang如果采纳,就会给出一个我没有想到却更加强大的解决方案。这次就是这样。

下面就是可以将所有子域名都转化为模块的路由规则,来自Yii官方论坛的一个帖子

XML/HTML代码
  1. 'http://<_m:\w+>.xxx.com<_q:.*>/*'=>'<_m><_q>',  
规则写在main.php中的组件配置数组里面:
PHP代码
  1. 'urlManager'=>array(  
  2.     'urlFormat'=>'path',  
  3.     'showScriptName' => false,  
  4.     'rules’=>array(  
  5.         'http://<_m:\w+>.xxx.com<_q:.*>/*'=>'<_m><_q>',  
  6.     )  
  7. ),  

如果仅仅是一个模块(假设是user)需要绑定子域名,可以这样写规则:
XML/HTML代码
  1. 'http://user.xxx.com<_q:.*>/*'=>'user<_q>',  
如果是若干模块需要绑定子域名,可以这样写:
XML/HTML代码
  1. 'http://<_m:(user|admin|photo)>.xxx.com<_q:.*>/*'=>'<_m><_q>',  

在使用的时候我注意到,如果是www开头的网址也会被转向到www模块,那么你可以使用(A|B|C)这样的规则选择要启用的模块,或者使用正则来滤掉www。

另外在路由规则里面,如果某一条匹配,则不会向下进行匹配。这是需要注意的,但是正是这样,路由才更高效,更灵活。

官方的URL管理说明文档:http://www.yiiframework.com/doc/guide/topics.url ,中文的我还没有翻译,等翻译之后,会发布到官方网站。

--EOF--

正如上面作者所说,官方这一段确实还是英文,可以看这里:http://www.yiiframework.com/doc/guide/1.1/zh_cn/topics.url,不过也很容易理解

以下来自官方:

Parameterizing Hostnames

Starting from version 1.0.11, it is also possible to include hostname into the rules for parsing and creating URLs. One may extract part of the hostname to be a GET parameter. For example, the URL http://admin.example.com/en/profile may be parsed into GET parameters user=admin and lang=en. On the other hand, rules with hostname may also be used to create URLs with paratermized hostnames.

In order to use parameterized hostnames, simply declare URL rules with host info, e.g.:

PHP代码
  1. array(  
  2.     'http://<user:\w+>.example.com/<lang:\w+>/profile' => 'user/profile',  
  3. )  

The above example says that the first segment in the hostname should be treated as user parameter while the first segment in the path info should be lang parameter. The rule corresponds to the user/profile route.

Note that CUrlManager::showScriptName will not take effect when a URL is being created using a rule with parameterized hostname.

Also note that the rule with parameterized hostname should NOT contain the sub-folder if the application is under a sub-folder of the Web root. For example, if the application is under http://www.example.com/sandbox/blog, then we should still use the same URL rule as described above without the sub-folder sandbox/blog.

 

Tags: yii, 参考