Removing a portion of the URL in Yii 2.0

こ雲淡風輕ζ 提交于 2019-12-13 06:49:24

问题


If I enter the URL:

http://localhost/third/web/calculator

it just works fine. I now want to remove the web portion from the URL. I currently do not have .htaccess. And if I enter http://localhost/third/calculator it shows object not found.

I added this .htaccess in the root folder of the project:

Options +FollowSymlinks
RewriteEngine On

RewriteCond %{REQUEST_URI} ^/third/(assets|css)
RewriteRule ^assets/(.*)$ web/assets/$1 [L]
RewriteRule ^css/(.*)$ web/css/$1 [L]

RewriteCond %{REQUEST_URI} !^/third/web/(assets|css)/
RewriteCond %{REQUEST_URI} !index.php
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ web/index.php

Now if I enter http://localhost/third/calculator it shows the congratulations page of yii2, instead of the calculator page. If click in any other tabs like login with link <a href="<?php echo Yii::$app->request->baseUrl;?>/login"><span class="glyphicon glyphicon-log-in"></span> Login</a> the url shows the web still.


回答1:


First you change config->web.php

'components' => [
    'urlManager' => [
        'class' => 'yii\web\UrlManager',
        'enablePrettyUrl' => true,
        'showScriptName' => false,
    ],
]

Add .htaccess file in your project root directory

# prevent directory listings
Options -Indexes
IndexIgnore */*

# follow symbolic links
Options FollowSymlinks
RewriteEngine on
RewriteRule ^(/.+)?$ web/$1 [L,PT]
RewriteRule ^(.+)?$ web/$1

Also you have to add .htaccess file in your_project->web directory

RewriteEngine on

# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule . index.php



回答2:


Here is my settings:

1) .htaccess in the root folder

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_URI} !^/(web)
RewriteRule (.*) web/$1

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . web/index.php
</IfModule>

2) config/web.php

'components' => [
    'request' => [
        // ...
        'baseUrl' => '' // don't forget about this string
    ],
    // ...
    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'enableStrictParsing' => true,
        'rules' => [
            // ...
        ],
    ],
],


来源:https://stackoverflow.com/questions/38584390/removing-a-portion-of-the-url-in-yii-2-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!