【问题标题】:Enable clean URL in Yii2在 Yii2 中启用干净的 URL
【发布时间】:2014-12-18 22:59:00
【问题描述】:

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

【问题讨论】:

  • 我建议对 Yii2 项目使用 Yii 高级改进版,因为其中已经解决了许多此类问题,并且源提供者已经完成了许多其他事情。只是一个建议
  • 基本上都是关于 mod_rewrite,在 Yii2 文档本身中有很好的描述。

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


【解决方案1】:

我让它在 yii2 中工作。为Apache 启用mod_rewrite。 对于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 的情况下,在backend/webfrontend/web 文件夹中创建.htaccess 文件,并在urlManager 中添加urlManager 组件common/config/main.php

【讨论】:

  • 你应用的规则对我有帮助,我试过没有规则但总是出错。
  • 好吧,看来这个更好。请记住,.htaccess 文件仅在您使用 apache 时适用 - 它与 nginx 和其他 Web 服务器不同。我正在删除第二个(我的)答案。
  • 有时控制器和动作有一个破折号- 字符。我必须将 \w+ 更改为 [\w\-]+ 才能使其与那些一起使用。
  • 感谢您为高级模板添加答案
  • @YasinPatel 你说得对,它不适用于高级模板。建议任何其他高级模板的解决方案。
【解决方案2】:

第一个重点是

Module_Rewrite 在您的服务器上启用(LAMP、WAMP、XAMP..etc) 在 yii2 框架中做 URL rewiring 创建一个 .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>',
   ),
],

【讨论】:

  • 当控制器和操作名称中有连字符/破折号时,您需要将\w+ 替换为[\w\-]+
【解决方案3】:

对我来说,问题是:

  1. 如上所述,Web 文件夹中缺少 .htaccess。
  2. AllowOverride 指令设置为 None,这会禁用 URL 重写。我将其更改为 All,现在漂亮的 URL 可以正常工作了。
<Directory "/path/to/the/web/directory/">
  Options Indexes 
  FollowSymLinks MultiViews 
  AllowOverride All 
  Require all granted
</Directory>

【讨论】:

  • FollowSymLinks MultiViews 这一行在我的配置文件中产生了语法错误,我不得不这样做Options Indexes FollowSymLinks
【解决方案4】:

首先,在你的 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 => localhost/yii2project/about-us localhost/yii2project/site/contact => localhost/yii2project/contact-us localhost/yii2project/site/index => localhost/yii2project/home

您可以通过

访问您的管理员

localhost/yii2project/backend/web

【讨论】:

  • 在服务器进行这些配置之后,我们还需要启用 mod_rewrite。在终端运行这些命令 sudo a2enmod rewrite , sudo service apache2 restart 现在转到“/etc/apache2/apache2.conf”打开它你最喜欢的编辑器并将“AllowOverride none”更改为“AllowOverride All ”保存您的更改,您需要通过上述命令再次重新启动 Apache。文件将处于只读模式。所以确保root登录所以首先添加“su”命令suvim /etc/apache2/apache2.confsudo service apache2 restarttutsnare.com/remove-index-php-from-url-in-yii2
【解决方案5】:

在 nginx 上这样配置

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

【讨论】:

  • 如果我确实更改了 default.conf,然后浏览 url "IP/backend/web/site/login" 然后它显示页面 "IP" 但不是我的后端登录,知道吗?
  • 刚刚做了两个位置到高级 yii2 应用程序。将后端与前端分开。并为后端“root IP/backend/web;”做对于前端“root IP/frontend/web;”在你的 default.conf 文件中
【解决方案6】:

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

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

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

【讨论】:

    【解决方案7】:

    第 1 步:.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]
    

    第 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' =&gt; []中添加。

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

    以上步骤对我有用。

    【讨论】:

      【解决方案8】:

      分步说明

      步骤 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】:

        什么对我有用-
        在我的 Yii2 项目的根文件夹中创建一个 .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 文件网络文件夹:

        frontend/web/
        

        并添加了以下内容-

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

        然后在这里添加urlmanager-

        projectFolder/common/config/main.php
        

        对我来说它不存在,所以添加了这个-

        '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' =&gt; [] 中。

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

        【讨论】:

          【解决方案10】:

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

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

          Step2:创建 .htaccess 文件 inset web 文件夹 eg: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
          

          【讨论】:

            【解决方案11】:

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

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

            【讨论】:

              【解决方案12】:

              如果你已经安装了 yii2 应用主题
              转到基本/网络/
              inside -> .htaccess "如果不存在则粘贴下面的代码"

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

              然后转到配置/
              在 web.php uncomment 行内从 47 到 52(行可能会更改)或类似的东西..

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

              【讨论】:

                【解决方案13】:

                我安装了这个框架的新版本。

                backend/config/main.php 中,您可以看到注释的代码,您可以使用它并为frontend 文件夹执行此操作。

                【讨论】:

                  【解决方案14】:

                  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 
                  

                  【讨论】:

                  • 感谢您对 StackOverflow 的贡献。请在此处使用英语。
                  猜你喜欢
                  • 2013-06-29
                  • 2015-03-12
                  • 1970-01-01
                  • 2015-05-28
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多