我正在尝试开发一个 vuejs 前端网站,使用 wordpress 作为 headless CMS。
到目前为止一切都很好,但有一件事让我担心。
前端位于domain.com/index.html,因此我将wordpress根文档index.php重命名为_index.php。为了阅读我添加的/wp-json/v2/API
RewriteRule ^wp-json/(.*) /_index.php [L]
到 apache .htaccess 文件以重定向调用。
但是,如果我现在还想使用 ?json= 调用旧的 json API,则
RewriteRule ?json(*) /_index.php [L]
或
RewriteRule ^?json=(.*) /_index.php [L]
不起作用。
我如何使用这两个 API,不知道为什么 rewriteRule 不起作用。
这就是我的样子
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^wp-json/(.*) /_index.php [L]
#RewriteRule ^?json(*) /_index.php [L]
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
顺便问一下:有没有办法使用 json API V2 将页面递归输出为父/子树?
最佳答案
为什么?如果您在请求根目录时遇到so I renamed the wordpress root document
index.php
to_index.php
index.php
优先问题,请重置 DirectoryIndex
。例如:
DirectoryIndex index.html
现在,请求目录时仅检查 index.html
。 (之前可能设置为 DirectoryIndex index.php index.html
之类的内容,因此 index.php
会优先。)
RewriteRule ^?json=(.*) /_index.php [L]
RewriteRule
模式仅与 URL 路径匹配,这特别排除了查询字符串。要匹配查询字符串,您需要使用单独的条件(RewriteCond
指令)并检查QUERY_STRING
服务器变量。
例如:
RewriteCond %{QUERY_STRING} ^json=
RewriteRule ^$ index.php [L]
正则表达式 ^$
确保仅匹配文档根目录的请求,而不匹配任何 URL 路径。
^json=
匹配任何以 json=
开头的查询字符串。 (.*)
部分不是必需的。 QUERY_STRING
服务器变量不包含 ?
分隔符本身。
注意:正则表达式 ?json(*)
(在第一个示例中)无效,您期望得到 500 响应(如果在 Apache 上),因为正则表达式将无法编译。
替换字符串上的 /
前缀不是必需的,应该避免。 (现在使用了 RewriteBase
指令 - 无论如何,这里实际上并不需要该指令。)
所以,总而言之,它看起来像这样,有一些小的调整:
# Limit the directory index to "index.html" only
DirectoryIndex index.html
RewriteEngine On
# Pass Authorization header to backend on CGI
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Stop early if the front-controllers are already reached
RewriteRule ^index\.(html|php)$ - [L]
# WordPress API
RewriteRule ^wp-json/ index.php [L]
RewriteCond %{QUERY_STRING} ^json=
RewriteRule ^$ index.php [L]
# VueJS
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.html [L]
关于wordpress - 如何在 apache 中为 WordPress json API v1 和 v2 重写规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74804376/