NGINX伪静态问题:跳转PHP后如何保持友好URL显示
NGINX实现友好URL(地址栏保留伪静态路径)
要实现访问www.mydomain.com/products时,内部解析到products.php但地址栏不显示PHP文件名,核心是要内部重写请求而非外部跳转。你之前的配置问题出在使用了不必要的proxy_pass,或是未正确控制重写规则的触发逻辑,导致地址栏暴露实际PHP路径。
单个路径的解决方案(仅针对/products)
直接修改/products对应的location配置,使用内部重写规则:
server { server_name mydomain.com www.mydomain.com; root /var/www/mydomain.com; index index.html index.php; location / { try_files $uri $uri/ =404; } # 精确匹配/products请求,内部转向products.php location = /products { rewrite ^ /products.php last; } location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; # 确保脚本路径正确,避免触发意外跳转 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } location ~ /\.ht { deny all; } }
关键说明:
location = /products是精确匹配,仅对/products这个单一路径生效,不会影响/products/xxx这类子路径请求。rewrite ^ /products.php last;中的last指令会让NGINX停止当前location的处理,重新匹配新的URI(/products.php),进而进入PHP处理location完成解析,整个过程是内部操作,不会向浏览器发送跳转响应,因此地址栏始终显示/products。- 无需使用
proxy_pass:你的场景是直接解析本地PHP文件,用fastcgi处理即可,反向代理完全多余,还可能引发跳转问题。
通用规则方案(所有/xxx对应/xxx.php)
如果需要让所有类似/xxx的请求都对应/xxx.php,可以简化为全局规则:
server { server_name mydomain.com www.mydomain.com; root /var/www/mydomain.com; index index.html index.php; # 全局处理:优先访问文件/目录,不存在则尝试对应PHP文件 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; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } location ~ /\.ht { deny all; } }
为什么之前的配置失效?
proxy_pass http://localhost/products.php:这种反向代理方式会将请求转发到本地HTTP服务,若后端配置了目录跳转或其他规则,可能会将PHP路径暴露到地址栏,且完全没必要绕这个圈子。- 未精确匹配的
try_files:如果/products是实际存在的目录,try_files $uri $uri/ /products.php会优先匹配$uri/,触发目录自动补全跳转(比如地址栏变成/products/),间接导致路径变化。
内容的提问来源于stack exchange,提问作者Lukáš Ježek
相关产品推荐
相关产品推荐

