SaidbakR
SaidbakR

Reputation: 13534

Yii2 get access only using pretty URLs

I'm using URL manager like the following:

'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [                
                'verses/view/<id:\d+>' => 'verses/view',                
            ],
        ],

It works fine to make access using mysite.com/verses/view/158. The problem is, it is still possible to access the same content using non pretty URL i.e using plain get parameter such as mysite.com/verses/view?id=158. I need any way to restrict the access using the pretty URL.

I have tried the following couples of rules separately, but nothing I have gotten:

  1. 'verses/view<?id=>' => 'Error404',
  2. 'verses/view?id=<\d+>' => 'Error404',

Upvotes: 0

Views: 79

Answers (2)

Sergey Okatov
Sergey Okatov

Reputation: 1420

Try using UrlManager parameter enableStrictParsing = true.

What happens. UrlManager checks all rulls and they all do not match the request. Thus, by default it checks all default rules. Among default rules it finds the rule with ?id= and preforms routing to that one.

So, in order to avoid that route, you need to list all possible routes in the UrlManger rules and make enableStrictParsing = true. The routes not listed in the config rules parameter will be ignored.

Upvotes: 1

Bizley
Bizley

Reputation: 18021

What is the point of such restriction?

Anyway, one way to do it is something like this:

public function actionView($id)
{
    if (strpos(\Yii::$app->request->getUrl(), '?') !== false) {
        throw new \yii\web\BadRequestHttpException;
    }
    // ... the rest of action
}

No changes in UrlManager needed.

Upvotes: 1

Related Questions