All non-www URLs redirect to www URL

Submitted by iraitc - 8 years ago

I made a filter for Laravel 5.0 , you can redirect non-www URLs to www URL and you don't need to write any difficult htaccess codes . Just put the filter in routes.php and use it for any Routes you want them to be with WWW . This snipped code is made by www.larabook.ir

<?php
// routes.php file

Route::filter('www',  function () {
    //Add the 'www.' to all requests
	$request=app('request');
	$host=$request->header('host');
	if (substr($host, 0, 4) != 'www.') {
		$request->headers->set('host', 'www.'.$host);
		return Redirect::to($request->path());
	}
});

Route::group(['before' => 'www'], function () {
	get('/', 'HomeController@index');
    // other routes here ...
});