.htaccess重定向WordPress插件API失败问题排查
WordPress插件API重写规则的URI匹配差异问题
我在WordPress站点开发了一个插件,内置了API接口。本地站点地址是http://localhost:81/site,需要把所有以http://localhost:81/site/api开头的请求(比如http://localhost:81/site/api/authentication/login)转发到http://localhost:81/site/wp-content/plugins/my_plugin/api/routes.php。
最初使用的.htaccess规则如下:
RewriteCond %{REQUEST_URI} ^/site/api/ [NC] RewriteRule ^/site/api/(.*)$ /site/wp-content/plugins/my_plugin/api/rotas.php [QSA,L]
但规则无效,查看error.log发现:
(...) [rewrite:trace3] (...) [perdir C:/myproject/site/] applying pattern '^/site/api/(.*)$' to uri 'api/authentication/login'
规则匹配的是/site/api,但实际对比的URI是api/authentication/login,于是修改规则为:
RewriteCond %{REQUEST_URI} ^api/ [NC] RewriteRule ^api/(.*)$ /site/wp-content/plugins/my_plugin/api/rotas.php [QSA,L]
此时日志显示:
(...) [perdir C:/myproject/site/] applying pattern '^api/(.*)$' to uri 'api/authentication/login' (...) [perdir C:/myproject/site/] RewriteCond: input='/site/api/authentication/login' pattern='^api/' [NC] => not-matched
RewriteRule的匹配字符串是正确的,但RewriteCond对比的是带/site前缀的URI。为什么两者处理URI时前缀情况不同?日志里更早的记录显示:
[perdir C:/myproject/site/] strip per-dir prefix: C:/myproject/site/api/authentication/login -> api/authentication/login
原因解析
这是Apache Rewrite模块的核心逻辑差异导致的:
- RewriteRule:当
.htaccess放在C:/myproject/site/目录下时,Apache会先自动移除当前目录对应的URI前缀(也就是/site/),只把剩余的路径部分(比如api/authentication/login)交给RewriteRule的匹配模式处理。所以第二个规则里的^api/(.*)$能正确匹配。 - RewriteCond:
%{REQUEST_URI}是Apache记录的完整请求路径,包含站点根目录的前缀/site/,也就是/site/api/authentication/login,所以用^api/去匹配自然会不生效。
解决办法
方法1:直接用RewriteRule(推荐)
不需要额外的RewriteCond,因为RewriteRule已经处理了目录前缀:
RewriteRule ^api/(.*)$ /site/wp-content/plugins/my_plugin/api/routes.php [QSA,L]
方法2:配合正确的RewriteCond
如果一定要用RewriteCond,需要匹配完整的请求URI:
RewriteCond %{REQUEST_URI} ^/site/api/ [NC] RewriteRule ^api/(.*)$ /site/wp-content/plugins/my_plugin/api/routes.php [QSA,L]
内容的提问来源于stack exchange,提问作者Marlon
相关产品推荐
相关产品推荐

