I'm building a small app that needs to redirect old URLs to the newer and cleaner URLs that Lumen provides.
Basically I want to route and possibly giving it a 301 redirect.
/something.php?id=1 -> /somethings/1
The problem is this code doesn't seem to work:
$app->get('/something.php?id={id}', function ($id) {
redirect()->route('somethings', ['id' => $id]);
});
This route is where I wanted to redirect this to:
$app->get('somethings/{id}', [
'as' => 'somethings', 'uses' => 'SomeController@show'
]);
This is supposed to work, but I can't seem to manage it.
I would also go the .htaccess route if that's better.
Adding this snippet into the public/.htaccess
file didn't seem to work either.
RewriteRule something\.php?id=(.+)$ somethings/$1 [R=301,L]
I'm not very handy with rewrites, so there could be something wrong that I'm totally missing here.
Anyone wanna point me in the right direction?
If you only want to get the value of id
from the old URL, you can resolve request
service inside the route and get the value of id
from there. Like this :
$app->get('somethings.php',function() use ($app){
dd($app['request']->id);
});
//localhost/somethings.php?id=1 ---> return "1"
You could do it in Lumen itself, but it'll be faster if you use .htaccess
:
RewriteCond %{QUERY_STRING} ^id=(\d+)$
RewriteRule ^something.php$ /somethings/%1 [R=301,L]
The above should be placed just below RewriteEngine On
. In addition, you should know that a condition only applies to the rule that follows. So, If you want to check another URI and query string, you'll need to repeat the above for that.
If you'd prefer to use Lumen, you can add this to your routing config:
$app->get('something.php', function() use ($app) {
$request = $app['request'];
$param = 'id';
if ($request->has($param)) {
if (preg_match('/[0-9]+/', $request->input($param))) {
return redirect()->route('somethings', ['id' => $request->input($param)]);
}
}
});
You didn't use the return
keyword, It should be:
return redirect()->route('somethings', ['id' => $id]);
Instead of
redirect()->route('somethings', ['id' => $id]);
If you are using Homestead, it runs nginx as the web server and not Apache. .htaccess is specific to Apache.