Programming
We provide developers and engineers the guides and tutorials they...
Search
We provide developers and engineers the guides and tutorials they...
Content is king. It's not just about how you're going to write, b...
Looking for an engaging connection with thousands of other people...
If you are running a Laravel project, you might be surprised to find out that your app routes are probably available on a number of different URLs.
One of urls on this website is:
https://thewebtier.com/articles
However it seems that the following url will also work:
https://thewebtier.com/index.php/articles
Similar problems will be for main website url.
Default url is:
https://thewebtier.com
But also the following urls will also work:
https://thewebtier.com/index.php
and
https://thewebtier.com/index.php?anything
This situation can cause that competition could create urls for those unwanted urls with index.php and search engines will see duplicated urls for our whole website and finally we don't know which urls will be displayed in search engines (those without index.php or those with it).
In this short tutorial, we'll look into the options and ways to remove index.php from the URL in Laravel.
public/index.phpThe most quick solution is to place the following code in your public/index.php file.
Also Read: Deploy Laravel App in Production
/*
* --------------------------------------------------------------------
* REMOVE index.php from URI
* --------------------------------------------------------------------
*/
if (strpos($_SERVER['REQUEST_URI'],'index.php') !== FALSE )
{
$new_uri = preg_replace('#index\.php\/?#', '', $_SERVER['REQUEST_URI']);
header('Location: '.$new_uri, TRUE, 301);
die();
}RouteServiceProvider.phpAnother method is to check for the route in RouteServiceProvider.php and issue a redirect.
protected function removeIndexFromUrl()
{
if (Str::contains(request()->getRequestUri(), '/index.php/')) {
$url = str_replace('index.php/', '', request()->getRequestUri());
if (strlen($url) > 0) {
header("Location: $url", true, 301);
exit;
}
}
}and register the method inside boot() method.
Also Read: Localization in Laravel
If your website is running on Nginx, you can also redirect using simple configurations within your nginx config.
if ($request_uri ~* "^/index\.php(/?)(.*)") {
return 301 $2;
}If your website is running on Apache server, simply add the following code within public/.htaccess file.
Also Read: One to Many Polymorphic Relation in Laravel
<IfModule mod_rewrite.c>
RewriteEngine On
# Redirect if index.php is in the URL
RewriteRule ^index.php/(.+) /$1 [R=301,L]
</IfModule>Let us know in the comments section below, if you've any questions.
Also Read: Why Laravel is best PHP Framework?