.htaccess 重定向到我的 api 时出现问题

问题描述 投票:0回答:1

我有一个 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,而“输入字符串”正在比较的是“/api/authentication”,所以我将 .htacess 更改为:

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

第一行表示现在正在使用正确的字符串进行搜索,第二行是之前显示的,现在是,但它与 /site/api 进行比较

为什么在第一个比较中删除了 /site 前缀,而在第二个比较中则没有?

这似乎发生在日志文件的前面:

[perdir C:/myproject/site/] strip per-dir prefix: C:/myproject/site/api/authentication/login -> api/authentication/login
php wordpress apache .htaccess
1个回答
0
投票

问题在于你的

RewriteRule
,而不是
RewriteCond

文档明确指出(这里的所有示例都表明了这一点),

RewriteRule
中的模式应用于请求的relative路径,因此无需前导斜杠,只要规则在分布式配置文件(“.htaccess”)。与在 central 配置中实现规则相反,规则与 absolut 路径匹配。
RewriteCond
模式始终与绝对路径匹配。

另外你的条件根本不需要。规则本身完全能够匹配请求的路径,所以保持简单:

RewriteRule ^site/api/(.*)$ /site/wp-content/plugins/my_plugin/api/rotas.php [QSA,L]

您可以轻松地编写一个规则,其模式与both的实现形式相匹配:只需将前导斜杠设为可选即可:

RewriteRule ^/?site/api/(.*)$ /site/wp-content/plugins/my_plugin/api/rotas.php [QSA,L]

如果您想继续使用分布式配置文件(因此http主机内容区域内的“.htaccess”文件),则需要在位于http主机内的文件中实现上述形式的规则主机

DocumentRoot
文件夹,而不是更下面的地方。否则,您的模式将不会应用于“完整”请求的路径(如果有的话)。再次,请参阅文档了解详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.