简体   繁体   English

URL重写htaccess规则-Apache

[英]URL Rewriting htaccess Rules - Apache

I am trying to create a rest API which will accept number of parameters as segmented url 我正在尝试创建一个REST API,该API可以接受多个参数作为分段URL

This is my current rewrite rule, which is working fine, but handles only one segmented variable.Here only one item category id is coming in segment. 这是我当前的重写规则,可以正常工作,但只处理一个分段变量,分段中只有一个项目类别ID。

     ^products/categories/([0-9]+)/?$ products.php?category_id=$1 [NC,L]
     products/categories/?category_id=10

What Iam trying to do is, I will pass some other id like brand_id and color id as segmented url like this Iam想要做的是,我将像brand_id和color id这样的其他id作为分段URL传递

    ^products/categories/([0-9]+)/([0-9]*)/([0-9]*)?$ products.php?category_id=$1 [NC,L] 

and expecting the url to be rewrite like following 并期望URL被重写,如下所示

    products/categories/?category_id=10&brand_id=5&color_id=7.

The above rewriting works fine if and only if I have supplied all the 3 ids and it fails if I miss any of the id. 仅当我提供了所有3个ID时,上述重写才能正常工作,并且如果我错过任何一个ID都将失败。 In my case, only category id is mandatory for the request and all other items are optional. 在我的情况下,对于请求,仅类别ID是必需的,而其他所有项目都是可选的。 How can I change the rewriting url here to make the second and third variable as an optional item ? 如何在此处更改重写URL,以使第二个和第三个变量成为可选项目?

Thanks 谢谢

See the below example 请参阅以下示例

Your URL http://test.com/products/categories/10/5/7 您的网址http://test.com/products/categories/10/5/7

HTACCESS HTACCESS

RewriteRule ^products/categories/([0-9]+)/([0-9] )/([0-9] )?$ index.php?category_id=$1&brand_id=$2&color_id=$3 [L,QSA] RewriteRule ^产品/类别/([[0-9] +)/([0-9] )/([0-9] )?$ index.php?category_id = $ 1&brand_id = $ 2&color_id = $ 3 [L,QSA]

you can get all all 3 parameter 您可以获取所有3个参数

If you want to create dynamic rule for parameters then check below 如果要为参数创建动态规则,请检查以下内容

For single parameters (category_id) 对于单个参数(category_id)

RewriteRule ^products/categories/([0-9]+)?$ index.php?category_id=$1 [L,QSA] RewriteRule ^产品/类别/([[0-9] +)?$ index.php?category_id = $ 1 [L,QSA]

For two parameters (category_id and brand_id) 对于两个参数(category_id和brand_id)

RewriteRule ^products/categories/([0-9]+)/([0-9]*)?$ index.php?category_id=$1&brand_id=$2 [L,QSA] RewriteRule ^产品/类别/([[0-9] +)/([0-9] *)?$ index.php?category_id = $ 1&brand_id = $ 2 [L,QSA]

For three parameters (category_id, brand_id and color_id) 对于三个参数(category_id,brand_id和color_id)

RewriteRule ^products/categories/([0-9]+)/([0-9] )/([0-9] )?$ index.php?category_id=$1&brand_id=$2&color_id=$3 [L,QSA] RewriteRule ^产品/类别/([[0-9] +)/([0-9] )/([0-9] )?$ index.php?category_id = $ 1&brand_id = $ 2&color_id = $ 3 [L,QSA]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM