General domain redirects (eg non-www to www)

In many cases I need to redirect some domain specific url’s, like:

example.com -> www.example.com

http://example.com -> https://example.com

www.example2.com -> www.example.com

etc…

I’m currently using htaccess, but it would be better if I could use Yii because it’s more clean (all redirects in one file) and you could do some custom things with the incoming domains (like keep statistics or create a flash message for the user)

Is this possible with Yii? Or is .htaccess still the way to go?

I think you were better off leaving this to the webserver. It is way cleaner, easier to maintain and it does not require to invoke PHP/Yii on every request.

I don’t see much difference in letting the webbrowser parse the .htaccess or php parsing the url rewrites, altough in theory .htaccess will be faster, this seems negligible… and with yii, you would have a lot more flexibility and you can also run it on non-apache servers

Enforcing a prepended www. is also possible on LigHTTPd and nginx. Of course not via a .htaccess, but still. And invoking PHP for this purpose is a huge overhead. Keep in mind: Yii is built in a way that PHP has to be invoked only if it is absolutely necessary. For what you are intending, PHP/Yii would have to be teared up for every file being served by the webserver. That is every CSS-file, every JavaScript and every image. Yes, you could absolutely do that. But the performance penalty won’t be nearly as negligible as you seem to think.

Da:Sourcerer is absolutely right. The web server config is the place for such redirects.

I see your point, but I don’t understand why Yii would have to rewrite any css/js. We’re talking about redirects, not rewrites. So Yii is loaded and before any client side code is loaded, it will redirect to the right location.

For now I will leave the rewrites in the .htaccess but I think there are situations where the flexibility of PHP is better suited for the job.

In this particular use case it doesn’t matter if Yii has to rewrite or redirect. It will allways require PHP/Yii for every request. Otherwise you wouldn’t be able to control them. Now taking into account that most clients issue 3 concurrent requests per domain, you are easily tripling your server load (in the best case).

If you really need URL manipulation capabilities above of what Apache provides you, you might want to take a peek at Lighty’s very own mod_magnet.

Follow up: Apache v2.3/2.4 is going to feature a mod_lua itself.