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

Nginx移除文件扩展名并保留参数配置问题求助

解决Nginx SEO友好URL配置问题

我来帮你搞定这两个Nginx配置的问题,咱们一步步调整你的配置:

问题1:处理/face/xxx到/face.php?name=xxx的重写

你需要添加一个专门的location块来匹配/face/开头的路径,把路径里的后缀部分作为name参数传递给face.php。在你的现有配置里加入这段:

# 匹配/face/xxx格式的URL,重写为带参数的php请求
location ^~ /face/ {
    rewrite ^/face/(.*)$ /face.php?name=$1 last;
}

这个配置的作用是:当用户访问/face/hello-stackoverflow123时,Nginx会内部重写为请求/face.php?name=hello-stackoverflow123,然后交给你的php处理块去执行,不会再返回404了。

问题2:实现faces.php自动重定向到/faces

你需要在server配置的最外层(或者在location /之前)添加一段重写规则,当用户直接访问.php后缀的文件时,自动跳转到无后缀的URL。可以这样写:

# 当请求的php文件存在时,重定向到无后缀的URL
if (-f $request_filename) {
    rewrite ^/(.*)\.php$ /$1 permanent;
}

这里的permanent是301永久重定向,对SEO更友好。这个规则会检查请求的.php文件是否存在,如果存在就跳转到去掉.php的路径,比如访问faces.php会自动跳转到/faces。

完整的配置示例

把这些整合起来,你的最终配置大概是这样:

server {
    # 这里是你的server其他配置,比如listen、server_name、root等
    
    # 问题2的重定向规则:php文件跳转到无后缀URL
    if (-f $request_filename) {
        rewrite ^/(.*)\.php$ /$1 permanent;
    }

    location / {
        try_files $uri $uri.html $uri/ @extensionless-php;
        index index.html index.htm index.php;
    }

    # 问题1的重写规则:处理/face/xxx格式的URL
    location ^~ /face/ {
        rewrite ^/face/(.*)$ /face.php?name=$1 last;
    }

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

    location @extensionless-php {
        rewrite ^(.*)$ $1.php last;
    }
}

注意:修改完配置后,记得执行sudo nginx -t检查配置语法是否正确,然后sudo systemctl reload nginx重启Nginx让配置生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:32:49