How To Remove index.php From URL In Laravel 9

Websolutionstuff | Jan-13-2023 | Categories : Laravel PHP

If you're a developer, you're likely to have frustration with "index.php" cluttering up your website's web addresses. It not only looks unprofessional but can also be an obstacle to achieving user-friendly, search-engine-optimized URLs.

Fortunately, in Laravel 9, the process of eliminating "index.php" from your URLs has become more straightforward than ever. In this blog, we will take you through the step-by-step process of removing "index.php" from your Laravel project's URLs, ensuring your web application not only performs better but also provides a sleek and modern user experience.

Let's dive in and make your Laravel application shine!
 

Example:

// Valid URL
https://valid-url-example.com/how-to-remove-index-php

// Invalid URL
https://valid-url-example.com/index.php/how-to-remove-index-php

 

There are multiple ways to remove index.php from the URL in laravel. 

  • Remove URL using the public/index.php file
  • Remove URL using RouteServiceProvider
  • Redirect with Nginx
  • Redirect with .htaccess

 

Example: Remove URL using the public/index.php file

In this example, we will simply add the below code to the public/index.php file.

if (strpos($_SERVER['REQUEST_URI'],'index.php') !== FALSE )
{
    $new_uri = preg_replace('#index\.php\/?#', '', $_SERVER['REQUEST_URI']);
    header('Location: '.$new_uri, TRUE, 301);
    die();
}

 

Example: Remove URL using RouteServiceProvider

In this example, we will remove/redirect the URL using the RouteServiceProvider.php file.

app/Providers/RouteServiceProvider.php

<?php
  
namespace App\Providers;
  
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
  
class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to the "home" route for your application.
     *
     * This is used by Laravel authentication to redirect users after login.
     *
     * @var string
     */
    public const HOME = '/home';
  
    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
  
        $this->configureRateLimiting();

        $this->removeIndexPHPFromURL();
  
        $this->routes(function () {
            Route::prefix('api')
                ->middleware('api')
                ->namespace($this->namespace)
                ->group(base_path('routes/api.php'));
 
            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/web.php'));
        });
    }     
  
    /**
     * Configure the rate limiters for the application.
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
        });
    }

    protected function removeIndexPHPFromURL()
    {
        if (Str::contains(request()->getRequestUri(), '/index.php/')) {
            $url = str_replace('index.php/', '', request()->getRequestUri());
  
            if (strlen($url) > 0) {
                header("Location: $url", true, 301);
                exit;
            }
        }
    }
}

 

Example: Redirect with Nginx

If you work with Nginx, then you can redirect the URL using the following code.

if ($request_uri ~* "^/index\.php(/?)(.*)") {
    return 301 $2;
}

 

Example: Redirect with .htaccess

In this example, you can add the below code to the .htaccess file and simply redirect to the main URL.

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Redirect index.php URL
    RewriteRule ^index.php/(.+) /$1 [R=301,L]
</IfModule>

 

Conclusion

Removing 'index.php' from your URL is a crucial step towards achieving cleaner and more user-friendly web addresses. We've explored the process thoroughly in this blog, breaking down the essential steps to help you streamline your website's URLs.

By following these techniques, you not only enhance the aesthetics of your website but also improve its SEO and overall user experience. Laravel 9's flexibility and customization options make it easier to achieve this.

So, implement these methods and transform your URLs from cluttered to clean, ensuring that your website not only looks professional but also performs at its best.
 


You might also like:

Recommended Post
Featured Post
How to Get Random Record in Laravel 10
How to Get Random Record in La...

Here you will learn how to get random records from DB in laravel using the inRandomOrder() method. Explore an...

Read More

Nov-10-2023

How To Create Middleware For XSS Protection In Laravel 8
How To Create Middleware For X...

In this tutorial we will see how to create middleware for xss protection in laravel 8. Cross-site scripting is...

Read More

Dec-22-2021

The Best Laravel Tips & Tricks for Migrations
The Best Laravel Tips & Tricks...

Migrations are an essential part of any Laravel project, allowing developers to easily manage and update their database...

Read More

Oct-23-2023

How to Upgrade PHP 7.4 to 8.0 in Ubuntu
How to Upgrade PHP 7.4 to 8.0...

Hey there! I recently faced the need to upgrade my PHP version from 7.4 to the latest 8.0 on my Ubuntu server. It might...

Read More

Nov-06-2023