apache.htaccessyii2clean-urlsyii-url-manager

yii2 rest api url rewriting (hide directories)


I would like to use clean urls on my yii2 rest api.

I'm having clean urls for my frontend application but I'm failing to create clean urls for my yii2 rest api application.

I created the rest api by following the tutorial (Yii2: RESTful api: tutorial). The rest api uses a module for versioning.

Two .htaccess files have been created. One file in my root and an another one in my "api/web" directory.

root .htaccess file

RewriteEngine on
# prevent directory listings
Options -Indexes
IndexIgnore */*

# follow symbolic links
Options FollowSymlinks

RewriteCond %{HTTP_HOST} ^api.localhost [NC]
RewriteRule ^(.*)$ api/web/$1 [L,PT]

'api/web' .htaccess file

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?r=$1 [L,QSA]

Browsing to 'http://api.localhost.com/v1/music' gives a 404 page not found error.

While 'http://api.localhost.com/api/web/v1/music' returns results

(I would like to hide 'api/web/' in my url)


Solution

  •    'request' => [
            'baseUrl' => str_replace('/api/web', '', (new \yii\web\Request())->getBaseUrl()),
    
        ],
    

    Add this request component config in your main api config