在Nginx中将/file name重定向到file-name.php

在Nginx中将/file name重定向到file-name.php,php,nginx,Php,Nginx,我的结构项目 - index.php - abc.php - folder/ ---- def.php 我的nginx.conf server { listen 80 default_server; root /var/www/public; index index.html index.htm index.php; server_name _; location / { try_files $uri $uri/ /index.p

我的结构项目

- index.php
- abc.php
- folder/
---- def.php
我的nginx.conf

server {
    listen 80 default_server;

    root /var/www/public;

    index index.html index.htm index.php;

    server_name _;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location /index.php {
        include        snippets/fastcgi-php.conf;
        fastcgi_param  SCRIPT_FILENAME $request_filename;
        fastcgi_pass   unix:/var/run/php/php7.4-fpm.sock;
    }
}
如何将nginx.conf更改为对href使用
domain/abc
而不是
domain/abc.php

谢谢

这通常被称为“无扩展PHP”,有很多解决方案,这只是其中之一:

location / {
    try_files $uri $uri/ @php;
}
location @php {
    try_files $uri.php $uri/index.php /index.php =404;

    include        snippets/fastcgi-php.conf;
    fastcgi_param  SCRIPT_FILENAME $request_filename;
    fastcgi_pass   unix:/var/run/php/php7.4-fpm.sock;
}
如果希望以
.php
结尾的URI也能工作,请添加:

location ~* ^(.*)\.php$ { return 301 $1$is_args$args; }
这通常被称为“无扩展PHP”,有许多解决方案,其中只有一个:

location / {
    try_files $uri $uri/ @php;
}
location @php {
    try_files $uri.php $uri/index.php /index.php =404;

    include        snippets/fastcgi-php.conf;
    fastcgi_param  SCRIPT_FILENAME $request_filename;
    fastcgi_pass   unix:/var/run/php/php7.4-fpm.sock;
}
如果希望以
.php
结尾的URI也能工作,请添加:

location ~* ^(.*)\.php$ { return 301 $1$is_args$args; }

高性能解决方案只是指定所需的位置,并将其映射到相应的PHP脚本

location = /abc {
    include        snippets/fastcgi-php.conf;
    fastcgi_param  SCRIPT_FILENAME $document_root/abc.php;
    fastcgi_pass   unix:/var/run/php/php7.4-fpm.sock;
}
这将确保脚本
/abc.php
处理
/abc

如果您还想“隐藏”访问
/abc.php
,可以添加:

location = /abc.php { 
    return 404;
}
之所以这么快,是因为精确匹配(带等号)不涉及前缀匹配和正则表达式处理


此外,我们不需要使用
try_文件
(它有)。具体地说,如果使用@RichardSmith的答案中的配置,它可能会为任意请求生成多达5个不必要的文件存在性检查,并为每个到
/abc
的请求生成3个文件存在性检查。高性能解决方案只是指定所需的位置,并将其映射到相应的PHP脚本

location = /abc {
    include        snippets/fastcgi-php.conf;
    fastcgi_param  SCRIPT_FILENAME $document_root/abc.php;
    fastcgi_pass   unix:/var/run/php/php7.4-fpm.sock;
}
这将确保脚本
/abc.php
处理
/abc

如果您还想“隐藏”访问
/abc.php
,可以添加:

location = /abc.php { 
    return 404;
}
之所以这么快,是因为精确匹配(带等号)不涉及前缀匹配和正则表达式处理

此外,我们不需要使用
try_文件
(它有)。具体地说,如果使用@RichardSmith提供的答案中的配置,可能会对任意请求产生多达5个不必要的文件存在性检查,对
/abc
的每个请求产生3个文件存在性检查