Enable clean URL in Yii2

后端 未结 11 1198
攒了一身酷
攒了一身酷 2020-11-27 12:36

How can I enable clean urls in Yii2. I want to remove index.php and \'?\' from url parameters. Which section needs to be edited in Yii2 for that?

11条回答
  •  天命终不由人
    2020-11-27 13:03

    First, create a .htaccess at root folder in your Yii2 project with following content:

    Options +Indexes
    
     
      RewriteEngine on
    
      RewriteCond %{REQUEST_URI} !^public
      RewriteRule ^(.*)$ frontend/web/$1 [L] 
    
    
    # Deny accessing below extensions
    
    Order allow,deny
    Deny from all
    
    
    # Deny accessing dot files
    RewriteRule (^\.|/\.) - [F]
    

    Create another .htaccess file in your web folders with following content:

    frontend/web/ add backend/web/ Don't forget to add .htaccess file to both web folders:

    RewriteEngine on
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d 
    
    RewriteRule . index.php
    

    Now It's done. Change your URL configuration in Yii2:

    getBaseUrl());
    
    
    $config = [
        'components' => [
            'request' => [
                // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
                'cookieValidationKey' => 'aiJXeUjj8XjKYIG1gurMMnccRWHvURMq',
                'baseUrl' => $baseUrl,
            ],
             "urlManager" => [
                'baseUrl' => $baseUrl,
                'enablePrettyUrl' => true,
                'showScriptName' => false,
                "rules" => [
                    "home" => "site/index",
                    "about-us" => "site/about",
                    "contact-us" => "site/contact",
                ]
            ]
        ],
    ];
    
    return $config;
    

    Your URL will change to:

    localhost/yii2project/site/about => localhost/yii2project/about-us localhost/yii2project/site/contact => localhost/yii2project/contact-us localhost/yii2project/site/index => localhost/yii2project/home

    You can access your admin through

    localhost/yii2project/backend/web

提交回复
热议问题