Remove index.php from url nginx laravel

Updated: 8th June 2022
Tags: nginx php

1: Redirect from index.php to / from any part of url

Remove every index.php from any part of url in url

server
{
  root /var/www/***
  index index.php;
  server_name mywebsite.com;

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

This will make 301 redirects, for example:

mywebsite.com/index.php => mywebsite.com/
mywebsite.com/index.php?q=query => mywebsite.com/?q=query
mywebsite.com/index.php/article => mywebsite.com/article
mywebsite.com/index.php/article/ => mywebsite.com/article/

mywebsite.com/folder/index.php => mywebsite.com/folder/
mywebsite.com/folder/index.php?q=query => mywebsite.com/folder/?q=query
mywebsite.com/folder/index.php/article => mywebsite.com/folder/article
mywebsite.com/folder/index.php/article/ => mywebsite.com/folder/article/

2: Redirect from index php to / (root)

Remove only index.php from root url

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

This will make 301 redirects, for example:

mywebsite.com/index.php => mywebsite.com/
mywebsite.com/index.php?q=query => mywebsite.com/?q=query
mywebsite.com/index.php/article => mywebsite.com/article
mywebsite.com/index.php/article/ => mywebsite.com/article/