Enable clean URL in Yii2

后端 未结 11 1023
攒了一身酷
攒了一身酷 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
    
    <IfModule mod_rewrite.c> 
      RewriteEngine on
    
      RewriteCond %{REQUEST_URI} !^public
      RewriteRule ^(.*)$ frontend/web/$1 [L] 
    </IfModule>
    
    # Deny accessing below extensions
    <Files ~ "(.json|.lock|.git)">
    Order allow,deny
    Deny from all
    </Files>
    
    # 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:

    <?php
    
    use \yii\web\Request;
    $baseUrl = str_replace('/frontend/web', '', (new Request)->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

    0 讨论(0)
  • 2020-11-27 13:04

    For me, the problem was:

    1. Missing .htaccess in the web folder just like mentioned above.
    2. The AllowOverride directive was set to None, which disabled URL rewrites. I changed it to All and now pretty URLs work nicely.
    <Directory "/path/to/the/web/directory/">
      Options Indexes 
      FollowSymLinks MultiViews 
      AllowOverride All 
      Require all granted
    </Directory>
    
    0 讨论(0)
  • 2020-11-27 13:07

    What worked for me-
    create a .htaccess at root folder of my Yii2 project, and added following-

    <IfModule mod_rewrite.c>
        Options +FollowSymlinks
        RewriteEngine On
    </IfModule>
    
    <IfModule mod_rewrite.c>
        RewriteCond %{REQUEST_URI} ^/.*
        RewriteRule ^(.*)$ web/$1 [L]
    
        RewriteCond %{REQUEST_URI} !^/web/
        RewriteCond %{REQUEST_FILENAME} !-f [OR]
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^.*$ web/index.php
    </IfModule>
    

    Created new .htaccess file web folders with following content:

    frontend/web/
    

    and added following-

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

    Then added urlmanager here-

    projectFolder/common/config/main.php
    

    For me it was not there, so added this as-

    'urlManager' => [
        'class' => 'yii\web\UrlManager',
        'enablePrettyUrl' => true,
        'showScriptName' => false,
       /* 'rules' => [
            '<controller:\w+>/<id:\d+>' => '<controller>/view',
            '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
            '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
    
        ],*/
    ],
    

    Make sure this code must be in 'components' => [].

    Restart my server and everything works fine.

    0 讨论(0)
  • 2020-11-27 13:09

    Step 1: Put .htaccess file in root.

    Options –Indexes
    
    <IfModule mod_rewrite.c> 
      RewriteEngine on
    
      RewriteCond %{REQUEST_URI} !^public
      RewriteRule ^(.*)$ frontend/web/$1 [L] 
    </IfModule>
    
    # Deny accessing below extensions
    <Files ~ "(.json|.lock|.git)">
    Order allow,deny
    Deny from all
    </Files>
    
    # Deny accessing dot files
    RewriteRule (^\.|/\.) - [F]
    

    Step 2: Put .htaccess file in frontend/web.

    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
    

    Step 3: Then changes in frontend/config/main.php. Following code need to be added inside 'components' => [].

    'request' => [
     'csrfParam' => '_csrf-frontend',
     'baseUrl' => '/yii-advanced', //http://localhost/yii-advanced
    ],
    
    'urlManager' => [
      'class' => 'yii\web\UrlManager',
      'showScriptName' => false, // Disable index.php
      'enablePrettyUrl' => true, // Disable r= routes
      'rules' => array(
              'about' => 'site/about',
              'service' => 'site/service',
              'contact' => 'site/contact',
              'signup' => 'site/signup',
              'login' => 'site/login',
      ),
    ],
    

    Above steps are worked for me.

    0 讨论(0)
  • 2020-11-27 13:09

    config/web.php

    $params = require __DIR__ . '/params.php';
    $db = require __DIR__ . '/db.php';
    
    
    $config = [
    'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'aliases' => [
    '@bower' => '@vendor/bower-asset',
    '@npm'   => '@vendor/npm-asset',
    ],
    'components' => [
    'assetManager' => [
    // override bundles to use local project files :
    'bundles' => [
    'yii\bootstrap4\BootstrapAsset' => [
    'sourcePath' => '@app/assets/source/bootstrap/dist',
    'css' => [
    YII_ENV_DEV ? 'css/bootstrap.css' : 'css/bootstrap.min.css',
    ],
    ],
    'yii\bootstrap4\BootstrapPluginAsset' => [
    'sourcePath' => '@app/assets/source/bootstrap/dist',
    'js' => [
    YII_ENV_DEV ? 'js/bootstrap.js' : 'js/bootstrap.min.js',
    ]
    ],
    ],
    ],
    
    'request' => [
    // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
    'cookieValidationKey' => 'V_Pj-uMLTPPxv0Be5Bwe3-UCC6EjGRuH',
    'baseUrl' => '',
    ],
    
    'formatter' => [
    'dateFormat' => 'dd/MM/yyyy',
    'decimalSeparator' => ',',
    'thousandSeparator' => '.',
    'currencyCode'      => 'BRL',
    'locale'        => 'pt-BR',
    'defaultTimeZone'   => 'America/Sao_Paulo',
    'class'         => 'yii\i18n\Formatter',
    ],
    'datehelper' => [
    'class' => 'app\components\DateBRHelper',
    ],
    'formatcurrency' => [
    'class' => 'app\components\FormatCurrency',
    ],
    'request' => [
    // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
    'cookieValidationKey' => '123456',
    
    ],
    'cache' => [
    'class' => 'yii\caching\FileCache',
    ],
    'user' => [
    'identityClass' => 'app\models\User',
    'enableAutoLogin' => true,
    ],
    'errorHandler' => [
    'errorAction' => 'site/error',
    ],
    'mailer' => [
    'class' => 'yii\swiftmailer\Mailer',
    // send all mails to a file by default. You have to set
    // 'useFileTransport' to false and configure a transport
    // for the mailer to send real emails.
    'useFileTransport' => true,
    ],
    'log' => [
    'traceLevel' => YII_DEBUG ? 3 : 0,
    'targets' => [
    [
    'class' => 'yii\log\FileTarget',
    'levels' => ['error', 'warning'],
    ],
    ],
    ],
    'db' => $db,
    
    'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'enableStrictParsing' => true,
    'rules' => [
    '' => 'site/index',                                
    '<controller:\w+>/<action:\w+>/' => '<controller>/<action>',
    ],
    ],
    
    ],
    'params' => $params,
    ];
    
    if (YII_ENV_DEV) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
    'class' => 'yii\debug\Module',
    // uncomment the following to add your IP if you are not connecting from localhost.
    //'allowedIPs' => ['127.0.0.1', '::1'],
    ];
    
    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
    'class' => 'yii\gii\Module',
    // uncomment the following to add your IP if you are not connecting from localhost.
    //'allowedIPs' => ['127.0.0.1', '::1'],
    ];
    }
    
    return $config; 
    

    arquivo .htaccess na pasta raiz

    <IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On
    </IfModule>
    <IfModule mod_rewrite.c>
    RewriteCond %{REQUEST_URI} ^/.*
    RewriteRule ^(.*)$ web/$1 [L]
    RewriteCond %{REQUEST_URI} !^/web/
    RewriteCond %{REQUEST_FILENAME} !-f [OR]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^.*$ web/index.php
    </IfModule>
    

    .htaccess dentro da pasta web/

    RewriteEngine on
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d 
    
    RewriteRule . index.php 
    
    0 讨论(0)
提交回复
热议问题