How to bypass CORS error without use index.php to the end of url?

i want to access api url in js script, but get CORS error in browser.
so i add bellow to /api/index.php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");

but, if requested url then work fine without error.
but, if requested url not work, get CORS error.

how to work without use “index.php” end of url? how to configure nginx to fix this?
i use nginx+php-fpm with debian 11 os.

thank you,