Nginx重写问题:/reviews/(动态值).php转/reviews/index.php?slug=$1失败
问题分析与解决方法
你的Nginx重写规则不生效有两个核心原因:
- Location匹配优先级冲突:Nginx中,正则表达式类型的
location ~ \.php$优先级高于前缀匹配的location /reviews/。当访问带.php后缀的URL时,请求会直接被~ \.php$的location捕获,根本没机会触发/reviews/里的重写规则,导致Nginx直接去查找对应路径的PHP文件,找不到就返回404。 - 正则表达式语法错误:你写的
(.*).php$中,.是正则的通配符(匹配任意单个字符),不是字面意义的点号,应该写成(.*)\.php$才能准确匹配.php后缀。
解决方案一:提升/reviews/ location的优先级
给/reviews/的location加上^~标记,让它优先于正则location匹配:
location / { index index.php index.html index.htm; try_files $uri $uri/ =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 ^~ /reviews/ { # 修正正则表达式,转义点号 rewrite ^/reviews/(.*)\.php$ /reviews/index.php?slug=$1 last; # 处理该路径下的静态文件或其他请求 try_files $uri $uri/ =404; } error_page 404 /404.php;
当访问/reviews/xxx.php时,会先进入^~ /reviews/的location执行重写,last标记会让Nginx重新发起请求匹配,此时重写后的/reviews/index.php会被~ \.php$的location处理,正常执行PHP并传递slug参数。
解决方案二:将重写规则移到server块级别
server块级别的rewrite会在所有location匹配之前执行,能绕过location优先级问题:
server { # 补充你的listen、server_name等基础配置 listen 80; server_name domain.com; root /path/to/your/webroot; # 把重写规则放在server块最上方 rewrite ^/reviews/(.*)\.php$ /reviews/index.php?slug=$1 last; location / { index index.php index.html index.htm; try_files $uri $uri/ =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; } error_page 404 /404.php; }
这种方式更简洁,无需调整location优先级,直接在请求进入location前完成重写。
内容的提问来源于stack exchange,提问作者aBe
相关产品推荐
相关产品推荐

