繁体   English   中英

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

[英]Redirect /file-name to file-name.php in 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.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 以使用domain/abc作为 href 而不是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; }

高性能解决方案是简单地指定所需位置,并将 map 指定到相应的 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由脚本/abc.php处理。

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

location = /abc.php { 
    return 404;
}

为什么这样很快,是因为精确匹配(带等号)不涉及前缀匹配和正则表达式处理。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM