Yii url manager only ID in url

2019-06-09 14:16发布

问题:

i have in YII for example domain: www.example.com/product-url-1234

how to set rules in urlManager and how to use controller/action/id

回答1:

If you want to use this url www.example.eu/product-url-1234

and suppose 'index' is the name of the action of the 'user' controller that will handle the request

Then create a rule like

'<id:.*?>'=>'user/index'

Now if you will use Yii::app()->createUrl('user/index',array('id'=>'product-url-1234'))

then it will give you the desired result.

And if you Visit this Url, User/Index will handle the request.



回答2:

You are trying forward all request to one controller at root level.

I Assumed that all your request are redirected product/view route

in your config go to URL section,

'(.*)'=>'product/view'
    'urlManager' => array(  
      'urlFormat' => 'path',  
      'showScriptName' => false,  
        'rules' => array(  
            '(.*)' => 'product/view',  
            'post/<id:\d+>/<title:.*?>' => 'post/view',  
            'posts/<tag:.*?>' => 'post/index',  
            '<controller:\w+>/<action:\w+>' => '<controller>/<action>',  
          ), 

that means you are capturing all your root requests to product controllers view action

Where you can get www.example.eu/product-url-1234 using
Yii::app()->request->requestUri in product/view

but this is not good way to capture all your incoming request to a single controller, the better way would be as follows.

www.example.eu/product/product-url-1234

then you have to change the configuration

'product/<product:.*?>'=>'product/view'
    'urlManager' => array(  
      'urlFormat' => 'path',  
      'showScriptName' => false,  
        'rules' => array(  
            'product/<product:.*?>' => 'product/view',  
            'post/<id:\d+>/<title:.*?>' => 'post/view',  
            'posts/<tag:.*?>' => 'post/index',  
            '<controller:\w+>/<action:\w+>' => '<controller>/<action>',  
          ),  

in your view action, you can get the url through $_GET['product']