3

What would be the easiest way to add .html and have it work both ways?

example.com/about -> works!

example.com/about.html -> works!

I can add ".html" to the route, but then it doesn't work without.

Route::get('about.html', function () {
 return 'About page';
});
user1040259
  • 6,369
  • 13
  • 44
  • 62
  • 1
    You should avoid using two different URIs for the same content. Search engines will see it as duplicate content, and will rank your site accordingly. Rather choose to keep it, or discard it. – Mike Rockétt Apr 28 '16 at 17:45
  • Thanks Mike. My issue is that I have a popular highly ranked site that currently works with and w/out the extension. I'm writing the site in Laravel now. If I were to force .html with a 301 redirect, then that would need to happen in .htaccess not Laravel? – user1040259 Apr 28 '16 at 17:56
  • 1
    you can also use a canonical url to determine the original source of your page and avoiding such problems with search engines (and still using your pages with and without extension) – zorx Apr 28 '16 at 18:05
  • Actually, @zorx is quite right - no need to fuss over redirects if your site already ranks well. Just use a canonical tag to make sure everything is peachy. – Mike Rockétt Apr 28 '16 at 18:55

1 Answers1

5

Try this one :

Route::get('about{extension}', function() {
    return 'About page';
})->where('extension', '(?:.html)?');

You can also use RouteServiceProvider to catch the extension if you have many pages that needs this pattern (thanks @Mike) :

//app/Providers/RouteServiceProvider.php

public function boot(Router $router)
{
  $router->pattern('extension', '(?:.html)?');
  parent::boot($router);
}

and then in your routes.php

Route::get('about{extension}', function() {
    return 'About page';
});
zorx
  • 1,861
  • 14
  • 16
  • 2
    You should also mention that the regex can be defined in the service provider so that `where` doesn't have to be repeated... – Mike Rockétt Apr 28 '16 at 17:44