Mod重写-使用查询字符串清除URL无效

时间:2019-04-12 16:13:10

标签: apache .htaccess mod-rewrite url-rewriting clean-urls

我有以下.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 ^/([^/]+)/([^/]+)$ $1/$1.php?endpoint=$2 [L]
    RewriteRule ^([^/]+)/([^/]+)/([^/]+)$ $1/$1.php?endpoint=$2&id=$3 [L]
    RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)$ $1/$1.php?endpoint=$2&id=$3&endpoint2=$4 [L]
    RewriteCond %{QUERY_STRING} ^(.*)$
    RewriteRule ^([^/]+)$ $1/$1.php  [L]
    RewriteRule ^([^/]+)/([^/]+)? $1/$1.php?endpoint=$2%1 [QSA,L]
    RewriteRule ^/([^/]+)/([^/]+)/([^/]+)? $1/$1.php?endpoint=$2&id=$3%1 [QSA,L]
    RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)? $1/$1.php?endpoint=$2&id=$3&endpoint2=$4%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)时,它才有效。

如何使它正常工作?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

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

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