Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

calin.ionut's avatar

laravel app using index.php in url

I have a website in laravel which is installed on a vps server using apache.

The virtualhost file for it is:

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public

    <Directory /var/www/example.com/public/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined   
RewriteEngine on
RewriteCond %{SERVER_NAME} =www.example.com [OR]
RewriteCond %{SERVER_NAME} =example.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

The problem that i discovered today is if i use in the url /index.php it still loads the homepage (even if I don`t have that route defined)

the homepage route is:

Route::any('/', 'HomeController@index')->name('homepage')

Why is this happening? Is there a setting in laravel to prevent this ?

0 likes
7 replies
tykus's avatar

index.php is a valid file in the public directory; any file in the public directory is publically accessible.

calin.ionut's avatar

@tykus How to remove it from the url ?

One solution would be using htaccess

  # Redirect if index.php is in the URL
    RewriteRule ^index.php/(.+) / [R=301,L]

but I don`t like working with htaccess.

Is there a laravel solution ?

tykus's avatar

That is what .htaccess is for.

If you really wanted to write it in Laravel, then a global middleware that checks for the first segment of the URL and redirects if required would achieve the same end. It comes with more overhead since the framework must be bootstrapped etc.; and it is more code that must be maintained

calin.ionut's avatar

this approach is not not working as expected:

 RewriteRule ^index.php/(.+) / [R=301,L]

If the request is /index.php - it still load the /index.php without redirect to /

If I use /index.php/category it redirects to /category (it remove the index.php)

I have tried another one:

RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) / [R=301,NE,L]

this works fine .... but the problem here is If I have: /index.php?test it redirects to /?test

Anyone know how can I change this rules to redirect 301 to / if there is index.php in the url ???

calin.ionut's avatar
calin.ionut
OP
Best Answer
Level 5

I have edited using QSD:

# Redirect if index.php is in the URL
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php / [R=301,NE,L,QSD]

And now it works :)

SjoerdZonneveld's avatar

Had the same. Adding AllowOverride All to a Directory Tag pointing to the root folder fixed it.

I.e.

<Directory /var/www/example.com/>
    AllowOverride All
</Directory>

Please or to participate in this conversation.