'nginx remove php extension after keep redirecting to diretory even has same name of php files

my default server config

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;
    
    index index.php index.html index.htm index.nginx-debian.html;

    server_name _;
    
    location / {
        try_files $uri $uri/ @extensionless-php;
        index index.html index.htm index.php;
    } 
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php/php-fpm.sock;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    }
    location @extensionless-php {
        rewrite ^(.*)$ $1.php last;
    }
    location ~ /\.ht {
        deny all;
    }
}

my root folder likes

var/www/html

  • service.php
  • service (diretory)
  • ㄴ index.php

when i connect with http://example/service here
just redirect to service/index.php not service.php
what i did wrong ??
i want use both of them

http://www.exmaple/service  -> service.php

and

http://www.example/service/  -> service/index.php

i'm using ubuntu 20.04 nginx 1.18.0 php 8.1



Solution 1:[1]

In try_files $uri $uri/ @extensionless-php;, the $uri/ term tests if service is a directory before you branch to @extensionless-php to rewrite the URI to service.php. You could just remove that term from the try_files statement, as long as that doesn't break another part of your website.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Richard Smith