简体   繁体   中英

URL Rewriting htaccess Rules - Apache

I am trying to create a rest API which will accept number of parameters as segmented 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.

     ^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

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

and expecting the url to be rewrite like following

    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. In my case, only category id is mandatory for the request and all other items are optional. How can I change the rewriting url here to make the second and third variable as an optional item ?

Thanks

See the below example

Your URL http://test.com/products/categories/10/5/7

HTACCESS

RewriteRule ^products/categories/([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

If you want to create dynamic rule for parameters then check below

For single parameters (category_id)

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

For two parameters (category_id and brand_id)

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

For three parameters (category_id, brand_id and color_id)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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