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.
1. public/index.php
The 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();
}
2. RouteServiceProvider.php
Another 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
3. Redirecting with Nginx
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;
}
4. Redirecting with Apache
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?