Yii 框架通過 urlManager 的路由規則實現二級域名綁定,核心在於利用 hostInfo 解析域名並映射到對應模塊。這種機制讓不同業務模塊能以獨立子域名訪問,提升項目架構清晰度與品牌辨識度。
在 protected/config/main.php 中配置 urlManager 組件:
'urlManager' => array(
'urlFormat' => 'path',
'showScriptName' => false, // 注意:布爾值 false 不需引號
'urlSuffix' => '.html',
'rules' => array(
// 將 test.jb51.net 映射到 blog 模塊
'https://test.jb51.net' => array('/blog', 'urlSuffix' => '', 'caseSensitive' => false),
),
),
當模塊下存在多個控制器(如 CommentController)時,需添加額外路由規則:
'rules' => array(
// 模塊首頁
'https://test.jb51.net' => array('/blog', 'urlSuffix' => '', 'caseSensitive' => false),
// 文章詳情頁
'https://test.jb51.net/post-' => array('/blog/post/view', 'urlSuffix' => '.html', 'caseSensitive' => false),
// 評論相關
'https://test.jb51.net/comment-' => array('/blog/comment/', 'urlSuffix' => '.html', 'caseSensitive' => false),
),
訪問 https://test.jb51.net/comment-1.html 將路由到 Blog 模塊的 Comment 控制器。
Windows: C:\Windows\System32\drivers\etc\hosts
Linux/Mac: /etc/hosts
127.0.0.1 www.jb51.net test.jb51.net
在 httpd.conf 或 httpd-vhosts.conf 中添加:
NameVirtualHost *:80
<VirtualHost *:80>
ServerAdmin admin@jb51.net
DocumentRoot "E:/wamp/www/k1029"
ServerName test.jb51.net
ErrorLog "logs/test.jb51.net-error_log"
CustomLog "logs/test.jb51.net-access_log" common
<Directory "E:/wamp/www/k1029">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
server {
listen 80;
server_name test.jb51.net;
root /var/www/k1029;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
需綁定多個子域名時,只需在 rules 數組中追加規則,並在 Apache/Nginx 中添加對應虛擬主機:
'rules' => array(
'https://blog.jb51.net' => array('/blog', 'urlSuffix' => '', 'caseSensitive' => false),
'https://shop.jb51.net' => array('/shop', 'urlSuffix' => '', 'caseSensitive' => false),
'https://api.jb51.net' => array('/api', 'urlSuffix' => '', 'caseSensitive' => false),
// 更多子域名...
),
showScriptName 是否為 false、URL 規則正則是否匹配、Apache Rewrite 模塊是否啟用main.php 中設置 'session' => array('cookieParams' => array('domain' => '.jb51.net'))https:// 協議,並配置 SSL 證書*.jb51.net 指向服務器 IP