Nice programing

Yii2에서 깨끗한 URL 사용

nicepro 2020. 11. 22. 20:32
반응형

Yii2에서 깨끗한 URL 사용


Yii2에서 깨끗한 URL을 어떻게 활성화 할 수 있습니까? index.php와 '?'를 제거하고 싶습니다. URL 매개 변수에서. 이를 위해 Yii2에서 어떤 섹션을 편집해야합니까?


yii2에서 작동합니다. 에 대해 활성화 mod_rewrite합니다 Apache. 다음을 basic template수행하십시오. 웹 폴더에 .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

그런 다음 구성 폴더 내에서 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생성하고 .htaccess내부 컴포넌트를 추가 하는 경우backend/webfrontend/weburlManagercommon/config/main.php


저에게 문제는 다음과 같습니다.

  1. 위에서 언급 한 것처럼 웹 폴더에 .htaccess가 없습니다.
  2. AllowOverride 지시문이 None으로 설정되어 URL 재 작성이 비활성화되었습니다. All로 변경했고 이제 예쁜 URL이 잘 작동합니다.
<Directory "/path/to/the/web/directory/">
  Options Indexes 
  FollowSymLinks MultiViews 
  AllowOverride All 
  Require all granted
</Directory>

첫 번째 중요한 점은

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

먼저 .htaccess다음 내용으로 Yii2 프로젝트에 루트 폴더를 만듭니다 .

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/add 두 웹 폴더에 파일을 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;

URL이 다음으로 변경됩니다.

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


nginx에서 그렇게 구성하십시오.

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

이 토론에 추가하기 위해-방금 Yii2를 설치했으며 config / web.php에 다음과 같은 주석 처리 된 코드가 포함되어 있습니다.

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

수락 된 답변에 .htaccess 파일을 추가하면 위의 주석을 제거하면 예쁜 URL이 작동합니다 (허용 된 답변의 "규칙"이 무엇인지 모르겠지만 모든 것이 작동하지 않는 것 같습니다).


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' => [].

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

위의 단계는 저에게 효과적입니다.


단계별 지침

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

끝난..


나를
위해 일한 것은 내 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' => [].

내 서버를 다시 시작하면 모든 것이 잘 작동합니다.


1 단계 : config / main.php 프로젝트에서 예 : frontend / config / main.php

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

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

#php_flag  display_errors        on
#php_value error_reporting       2039

왜 너희들은 yii2 공급 업체 폴더로 이동하지 않고 public $ enablePrettyUrl = true; "(물론 htaccess 변경과 함께)를 설정하지 않는지 모르겠습니다. 그것은 저에게 잘 작동했고 훨씬 더 간단합니다. 그리고 저는 하나의 htaccess 파일이 있습니다-프로젝트의 루트에 3 개의 다른 위치가 아닙니다. 또한 Advanced Yii2의 'config / main.php'프로그램에 대해 제안한 것을 수행했을 때 작동하지 않았습니다. 404s ying-yang. 내가 꺼내고 prettyUrls가 다시 잘 작동했습니다. Composer 업데이트로 인해 이런 식으로하지 말아야 할 수도 있지만 이에 대한 '가짜'솔루션이 너무 많아서 처리하는 데 지쳤습니다. 그것.


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 파스타 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 파스타 web/

RewriteEngine on

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

RewriteRule . index.php 

참고 URL : https://stackoverflow.com/questions/26525320/enable-clean-url-in-yii2

반응형