Mod 重写 - 清除 URL 查询字符串不起作用

Mod Rewrite - Clean URL with query string not working

我有以下 .htaccess 文件。

<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 %{QUERY_STRING} ^$
    RewriteRule ^/([^/]+)/([^/]+)$ /.php?endpoint= [L]
    RewriteRule ^([^/]+)/([^/]+)/([^/]+)$ /.php?endpoint=&id= [L]
    RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)$ /.php?endpoint=&id=&endpoint2= [L]
    RewriteCond %{QUERY_STRING} ^(.*)$
    RewriteRule ^([^/]+)$ /.php  [L]
    RewriteRule ^([^/]+)/([^/]+)? /.php?endpoint=%1 [QSA,L]
    RewriteRule ^/([^/]+)/([^/]+)/([^/]+)? /.php?endpoint=&id=%1 [QSA,L]
    RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)? /.php?endpoint=&id=&endpoint2=%1 [QSA,L]
</IfModule> 

我想将 api 端点(干净的 url 格式,在最后一个标记的末尾可能进行查询)重写为完全如下所示的查询字符串格式。

例子

api/users/123/actionitems

正在阅读

api/api.php?endpoint=users&id=123&endpoint2=actionitems

{
    endpoint: users,
    id: 123,
    endpoint2: actionitems
}  

但我也想转换

api/users/123/actionitems?test=3

进入

api/api.php?endpoint=users&id=123&endpoint2=actionitems&test=3

{
    endpoint: users,
    id: 123,
    endpoint2: actionitems,
    test: 3
}  

没用。我只得到

api/api.php?endpoint=users&id=123&endpoint2=actionitems

当我输入

/api/users/123/actionitems?test=3

{
    endpoint: users,
    id: 123,
    endpoint2: actionitems
}  

并且只有当我在请求中键入 /api/users/123/actionitems&test=3 而不是问号 (/api/users/123/actionitems?test=3) 时它才有效。

如何让它工作?

您可以使用以下单个规则:

    Options +FollowSymlinks
    RewriteEngine On
    DirectoryIndex api.php
    FallbackResource index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^api/([^/]+)/([^/]+)/([^/]+)/?$  /api/api.php?endpoint=&id=&endpoint2= [QSA,L]

工作规则(到目前为止...)

<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 %{QUERY_STRING} ^(.*)$
    RewriteRule ^api/$ /api/api.php? [L]
    RewriteRule ^api/([^/]+)/$ /api/api.php?endpoint=%1 [QSA,L]
    RewriteRule ^api/([^/]+)/([^/]+)$ /api/api.php?endpoint=&id=%1 [QSA,L]
    RewriteRule ^api/([^/]+)/([^/]+)/([^/]+)$  /api/api.php?endpoint=&id=&endpoint2=%1 [QSA,L]
    #Disgard tokens after 3rd token
    RewriteRule ^api/([^/]+)/([^/]+)/([^/]+)/(.*)$  /api/api.php?endpoint=&id=&endpoint2=%1 [QSA,L]
</IfModule>