You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Nginx配置移除PHP网站URL中的.php后缀?

移除Nginx中PHP网站URL的.php后缀配置方法

要实现移除PHP网站URL里的.php后缀,你需要调整两处核心配置——让不带后缀的请求能正确解析到对应PHP文件,同时把带.php的旧URL重定向到无后缀版本(避免重复内容影响SEO),具体修改如下:

一、调整默认请求匹配规则

把原配置中location /块的try_files规则修改,添加$uri.php匹配项,让Nginx在找不到对应文件/目录时,自动尝试匹配带.php后缀的文件:

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

二、添加URL重定向规则(可选但推荐)

在server块的最上方(优先于其他location规则)添加重定向,将所有带.php的URL永久跳转到无后缀版本:

rewrite ^/(.*)\.php$ /$1 permanent;

修改后的完整配置

server {
    listen 80;
    server_name xx.com www.xx.com;
    root /var/www/xx;

    index index.html index.htm index.php;

    # 重定向带.php的URL到无后缀版本
    rewrite ^/(.*)\.php$ /$1 permanent;

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

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
     }

    location ~ /\.ht {
        deny all;
    }

}

注意事项

  • 修改完成后,先执行nginx -t测试配置语法是否合法,确认无误后执行systemctl reload nginx重启Nginx生效。
  • 如果网站有其他伪静态规则(如CMS的自定义 permalink),需确保重定向规则不会和它们冲突,必要时调整规则顺序。
  • 若需保留个别.php文件的后缀(如admin.php),可在重定向规则前添加例外:rewrite ^/admin\.php$ - last;

内容的提问来源于stack exchange,提问作者julian goncalves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 12:47:14