Yii2 - subdomain routing

2020-04-08 12:41发布

问题:

I want to use subdomain as id, and I need dynamic router to do this. In urlManager, I added this line:

"http://<user:\w+>.local.dev/<controller:\w+>/<action>" => '<controller>/<action>',

When I try any action, for example:

function actionMyAccount($user){
echo $user;...
}

I am not getting anything - the var isn't printed, and script stops working (screen is white). When I remove $user, the page is loading without any problems

How can I achieve subdomain router?

回答1:

I think your router mapping setting is OK. If you want it to be more precise:

"http://<user:[^www]\w+>.local.dev/<controller:\w+>/<action:\w+>" => '<controller>/<action>'

But to make it work, you'd better double check following two things:

First, your virtual host should have a *.local.dev

  • server_name in nginx
  • or ServerAlias in Apache

Then you can use dynamic controller's name as subdomain.

Second, your virtual host should have been configured rewrite rules correctly, refer to Yii2 doc.

e.g. for Apache, just create a .htaccess file under YOUR_APP/web/ folder with following content lines:

Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on
# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php


标签: yii routing yii2