Reputation: 1607
I'm wanting to redirect a short link domain in Laravel 5, e.g. xyz.com to examplesite.com whilst maintaining the URI request. For example:
xyz.com/something?foo=var
will redirect to:
example.com/something?foo=var
I've tried to use a domain group in the routes for this, but it did not seem to work on domain name level, only sub-domain. The other option I opted for is the MiddleWare route.
I have set up a working middleware "RedirectsMiddleware" and have the following in my routes file:
Route::group(['middleware' => ['redirects'] ], function () {
Route::get('/', 'HoldingSiteController@home');
});
My RedirectsMiddleware looks like this:
...
public function handle($request, Closure $next)
{
$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://';
$host = $_SERVER['SERVER_NAME'];
$defaulthost = 'example.com';
if($host != $defaulthost) {
return Redirect::to($protocol . $defaulthost . $_SERVER['REQUEST_URI']);
}
return $next($request);
}
...
When requesting just "example.com" or "example.com/?something=something" it redirects fine. Any route added to the end, e.g. "example.com/someroute" always throws an exception, queries strings have no effect. It appears to be looking for that route despite my MiddleWare redirecting:
NotFoundHttpException in RouteCollection.php line 161:
Upvotes: 1
Views: 5246
Reputation: 439
You'll need to use a wildcard route. The GET variables on the end of the url don't change the route in the way you're attempting. Visiting http://example.com/?var1=A "counts" as hitting a route defined as Route::get('/', function() {}) because you are visiting example.com/ with GET variable var1. In other words, GET variables are normally ignored for the purposes of determining which route the HTTP request should pick.
Wildcard matching uses the regular expression route method ->where()
Route::group(['middleware' => ['redirects'] ], function () {
Route::any('/{anything}', 'HoldingSiteController@home')
->where('anything', '.*');
Route::any('/', 'HoldingSiteController@home');
});
As seen above, you do also need the empty route any('/') for empty requests. This example also includes the "any" verb instead of the "get" verb to be a litte more greedy in its request matching.
Laravel - Using (:any?) wildcard for ALL routes?
https://laravel.com/docs/5.2/routing#parameters-regular-expression-constraints
Upvotes: 3