Find alternative routes on 404

My web-app has a lot of static content. My idea is to look for static content, whenever yii2 doesn’t find anything else. The mapping of URL to static content shall be done by PHP, and I don’t want to put all static content into a common route, e.g. the common approach to have “page/foo/bar” and an actionPage() in the SiteController is not what I want to achieve. I want to see it as “foo/bar” only.

I can think of several ways to do that, but everything seems awkward. In general I’d catch 404 exceptions, but I didn’t find a proper API for this, yet. Is there a canonical way to implement this?

Thanks for your help.

Generally you’d go the other way around: Configure your httpd/htaccess so that Yii is only involved if no static content is found.

Well, static is probably not precise enough. I’m talking about pages, which are produced by PHP without any context from the request. The main content is not data driven. But of course PHP is used to render the page template, which could contain sidebars e.g. announcing upcoming events. Otherwise I’d put the pages on static.example.com.

I traced through the framework and came up with the following idea. I’ll sub-class yii\web\Application to overload handleRequest() by a wrapper, which catches the NotFoundHttpException. It then tries it’s own logic to find something for $this->requestedRoute and either runs an appropriate action or re-throws.

Is there anything I’m missing?

Maybe create your own rule?

http://www.yiiframework.com/doc-2.0/yii-web-urlrule.html

Well the pattern for such a rule would be /.*/. It would be okay, if it is ensured to be the last rule. Will other rules take precedence?

Url manager will go through the list of rules from the top and use the first that matches the current request.

If that helps you already, go ahead.

Otherwise I was thinking of implementing your own rule, have a look at "Custom URL Rules" in this article: http://blog.neattutorials.com/yii2-routing-urlmanager/