0

I am working on a webapp. There are items accessible the way using item id in the url web.site/123, where 123 is item id. I want to redirect visitors to the full url page like web.site/123-the-item, and I also want to use full links within my website.

Any good idea how to do it?

I don't need the code, I am looking for a simple yet nice and effective idea. The title is obviously in the database, so there will be one select needed anyhow. But I am not sure, if I should redirect once and every single time visitor visits the site without checking if the url is full (doesn't seem nice) or should I check the url and redirect only if it doesn't match the title?

I am using nginx, php, mysql and laravel 5.2 in case there is a workaround for this scenario I am not aware of.

Panama Jack
  • 24,158
  • 10
  • 63
  • 95
notnull
  • 1,908
  • 3
  • 19
  • 25

2 Answers2

1

Try adding route like

Route::get('/{id}',['uses' => 'ContentController@byId'],'where'=>['id'=>'\d*']);

And in that action you can check in database if id exists and redirect user to proper url

Radek Adamiec
  • 502
  • 3
  • 10
  • I already have similar line in my routes file, and it all works just great. All I need now is to find out if redirect is needed or URL is correct. If needed, redirect to the full URL. – notnull Feb 01 '16 at 18:18
  • TL;DR you can't. You can only assume that if id is only digits and if you have corresponding record in database then you probably should redirect user, but you will never have 100% confident that you should – Radek Adamiec Feb 01 '16 at 18:20
  • how about comparing the last part of the URI (characters after id, which is always 6 digits long) with the title from db? If same, ok, no redir. If not, redirect to the full url – notnull Feb 01 '16 at 18:23
  • the part 'where'=>['id'=>'\d*'] makes sure that only url like: http://example.com/123 will be processed and not http://example.com/123-something – Radek Adamiec Feb 01 '16 at 18:26
  • I understand, but that's not so good, because you'd want to redirect wrong full urls as well. – notnull Feb 01 '16 at 18:40
  • Is't this what 404 is for :P? You can probably try to extract id with explode or preg_match function and then try to redirect user, but this is not bulletproof – Radek Adamiec Feb 01 '16 at 18:43
0

You can check use regular expressions to check the if the incoming request has just the id and have them mapped to particular routes. In the digit route you can redirect.

E.g. your route file should be something like this :

Route::get('item/{id}', function ($id) {
    //redirect to the full name route
})
->where('id', '[0-9]+');

Route::get('item', 'SomeController@somemethod');

Read more here.

Bharat Geleda
  • 2,692
  • 1
  • 23
  • 31