我刚刚在我的应用程序的 /api 目录的根目录中修改了我的 .htaccess 文件
通过删除我的问题中未显示的原始代码
RewriteBase /api
RewriteOptions InheritDown
在 api/ 之后,我只剩下以下处理偶数个令牌
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
DirectoryIndex api.php
FallbackResource index.php
RewriteCond %{REQUEST_URI} ^/api
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} ^/api
#RewriteRule (.*) $1
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^(.*/)([^/]+)/([^/]+) $1?$2=$3&%1 [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^([^/]+)/ $1/$1.php?%1 [L]
</IfModule>
http://<host>/api/key1/val1/key2/val2/key3/val3/key4/val4
现在在我的 php 脚本 api.php 中生成一个 json(输出键值对)
{
"key1": "val1",
"key2": "val2",
"key3": "val3",
"key4": "val4"
}
api.php 脚本
<?php
$requestURI = $_GET;
$method = strtolower($_SERVER['REQUEST_METHOD']);
switch ($method){
case 'get':
//var_dump($_GET);
echo json_encode($requestURI);
break;
case 'post':
echo json_encode($requestURI);
break;
case 'put':
echo json_encode($requestURI);
break;
case 'delete':
echo json_encode($requestURI);
break;
default:
// unimplemented method
http_response_code(405);
}
编辑:添加第一个条件块会产生更正确的输出,请参阅 cmets
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
DirectoryIndex api.php
FallbackResource index.php
#Redirects all existing files to the containing directory which
#then get handled by the 403 error document in .htaccess in /api folder
#but two token params get still rewritten as /?token1=token2
RewriteCond %{REQUEST_URI} ^/api
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule (.*/)([^/]+).php$ /$1 [R=302,L]
#Non exisitng resoruce then rewrite all items with one token to {'endpoint': <endpoint>}
RewriteCond %{REQUEST_URI} ^/api
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^api/([^/]+) api/endpoint/$1
#Rewrite non exisitng request to append query string to construct the query param form starting with question mark
RewriteCond %{REQUEST_URI} ^/api
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^(.*/)([^/]+)/([^/]+) $1?$2=$3&%1 [QSA,L]
#Append query string to end of question mark and write /api as api/api.php?token....
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule ^([^/]+)/ $1/$1.php?%1 [L]
</IfModule>