在Yii2中启用干净的URL

时间:2014-10-23 09:42:08

标签: yii2 clean-urls yii-url-manager

如何在Yii2中启用干净的网址。我想删除index.php和'?'来自url参数。需要在Yii2中编辑哪个部分?

15 个答案:

答案 0 :(得分:149)

我在yii2工作了。为mod_rewrite启用Apache。 对于basic template,请执行以下操作: 在Web文件夹中创建.htaccess文件并添加此

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

然后在config文件夹中,在web.php中添加组件

'urlManager' => [
    'class' => 'yii\web\UrlManager',
    // Disable index.php
    'showScriptName' => false,
    // Disable r= routes
    'enablePrettyUrl' => true,
    'rules' => array(
            '<controller:\w+>/<id:\d+>' => '<controller>/view',
            '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
            '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
    ),
],

如果advanced template.htaccessbackend/web文件夹中创建frontend/web个文件,并在urlManager common/config/main.php个组件>

答案 1 :(得分:13)

第一点是

在您的服务器上启用Module_Rewrite(LAMP,WAMP,XAMP..etc) 在yii2框架中进行URL重新布线创建一个.htaccess文件并放入/ 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

第二步

配置文件夹common/config/main-local.php添加到组件数组

'urlManager' => [
   'class' => 'yii\web\UrlManager',
   // Disable index.php
   'showScriptName' => false,
   // Disable r= routes
   'enablePrettyUrl' => true,
   'rules' => array(
      '<controller:\w+>/<id:\d+>' => '<controller>/view',
      '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
      '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
   ),
],

答案 2 :(得分:13)

对我来说,问题是:

  1. 如上所述,在网络文件夹中缺少.htaccess。
  2. AllowOverride指令设置为None,禁用URL重写。我把它改为All,现在漂亮的URL工作得很好。
  3. <Directory "/path/to/the/web/directory/">
      Options Indexes 
      FollowSymLinks MultiViews 
      AllowOverride All 
      Require all granted
    </Directory>
    

答案 3 :(得分:9)

首先,在Yii2项目的根文件夹中创建一个.htaccess,内容如下:

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]

在您的网络文件夹中创建另一个.htaccess文件,其中包含以下内容:

frontend/web/ 添加 backend/web/ 不要忘记将.htaccess文件添加到两个网络文件夹中:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d 

RewriteRule . index.php

现在已经完成了。在Yii2中更改您的URL配置:

<?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;

您的网址将更改为:

localhost/yii2project/site/about =&gt; localhost/yii2project/about-us localhost/yii2project/site/contact =&gt; localhost/yii2project/contact-us localhost/yii2project/site/index =&gt; localhost/yii2project/home

您可以通过

访问管理员

localhost/yii2project/backend/web

答案 4 :(得分:2)

在nginx上配置

location / {
    try_files $uri $uri/ /index.php$is_args$args;
}

答案 5 :(得分:2)

只是为了加入这个讨论 - 我刚安装了Yii2,它在config / web.php中包含以下注释掉的代码:

'urlManager' => [
  'enablePrettyUrl' => true,
  'showScriptName' => false,
  'rules' => [],
],

如果你在接受的答案中添加.htaccess文件,那么只需取消注释以上内容,漂亮的URL就可以了(我不知道接受的答案中的“规则”是什么,但是没有它们,一切似乎都有效)

答案 6 :(得分:1)

第1步:.htaccess文件放入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]

第2步:.htaccess文件放入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

第3步:然后更改frontend/config/main.php。以下代码需要在'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',
  ),
],

以上步骤对我有用。

答案 7 :(得分:0)

对我有用的东西 -
在我的Yii2项目的根文件夹中创建一个.htaccess,并添加了以下内容 -

frontend/web/

创建了包含以下内容的新.htaccess文件网络文件夹:

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

并添加了以下内容 -

projectFolder/common/config/main.php

然后在这里添加了urlmanager -

'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>',

    ],*/
],

对我而言,它不存在,所以将其添加为 -

'components' => []

确保此代码必须位于{{1}}。

重启我的服务器,一切正常。

答案 8 :(得分:0)

分步说明

第1步

在项目的根目录中添加.htaccess,其中包含以下内容:

Options +FollowSymLinks
IndexIgnore */*
RewriteEngine On
     RewriteCond %{REQUEST_URI} !^/(web)
    RewriteRule ^assets/(.*)$ /web/assets/$1 [L]
    RewriteRule ^css/(.*)$ web/css/$1 [L]
    RewriteRule ^js/(.*)$ web/js/$1 [L]
    RewriteRule ^images/(.*)$ web/images/$1 [L]
    RewriteRule (.*) /web/$1
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /web/index.php

第2步

在文件夹/ web中添加.htaccess文件,其中包含以下内容:

RewriteEngine On RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . index.php

第3步

在数组元素组件的文件/config/web.php中添加以下代码:

'request' => [
    // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
    'cookieValidationKey' => 'yYy4YYYX8lYyYyQOl8vOcO6ROo7i8twO',
    'baseUrl' => ''
],

//...

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        '' => 'site/index',                                
        '<controller:\w+>/<action:\w+>/' => '<controller>/<action>',
    ],
],

完成..

答案 9 :(得分:0)

Step1:在项目config / main.php中,例如:frontend / config / main.php

'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [],
        ]

Step2:创建.htaccess文件嵌入web文件夹,例如: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

#php_flag  display_errors        on
#php_value error_reporting       2039

答案 10 :(得分:0)

只需将以下代码添加到您的配置文件中即可。

'urlManager' => [
    'enablePrettyUrl' => true,
    'rules' => [
        // your rules go here
    ],
    // ...
]

答案 11 :(得分:0)

如果你已经安装了yii2应用主题
转到基本/网络/
内部 -> .htaccess“如果不存在,请在下面粘贴代码”

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

然后去配置/
在 web.php 中 取消注释 行从 47 到 52(行可能会改变)或类似的东西..

'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
        ],
    ],

答案 12 :(得分:-2)

您只需要更改两个文件,一个是后端/ web中的.htaccess文件,另一个是公共主文件

.htaccess文件

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

main.php

  'components' => [
       'cache' => [
        'class' => 'yii\caching\FileCache',
      ],
      'urlManager' => [
      'enablePrettyUrl' => true,
       'showScriptName' => false,
       'rules' => [
           '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
             '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
             '<controller:\w+>/<id:\d+>' => '<controller>/view',
          ],
      ],


      ],

答案 13 :(得分:-2)

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意大利面食

<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面食web/

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d 

RewriteRule . index.php 

答案 14 :(得分:-3)

我不知道为什么你们不进入yii2供应商文件夹并设置公共$ enablePrettyUrl = true;“(当然还有htaccess更改)。这对我来说很好,而且更简单我有一个htaccess文件 - 在项目的根目录中,而不是在3个不同的地方。另外,当我按照你们为高级Yii2中的'config / main.php'程序建议的那样,它没有用我从英阳那里得到了404分。我把它拿出来了,漂亮的美国人又恢复了工作。 也许我不应该这样做,因为Composer更新,但是有很多'伪造'的解决方案,我厌倦了处理它。