.htaccess remove “?page=”

I have two questions, both related:

  1. Using the example url: https://www.example.com/?page=foo.php

How do I use .htaccess to write that out as: https://www.example.com/foo

The second part

  1. Using the example url: https://www.example.com/?page=directory/bar.php

How do I use .htaccess to write that out as: https://www.example.com/directory/bar

edit:

In response to please show your current .htaccess

# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php74” package as the default “PHP” programming language.  
 <IfModule mime_module>
   AddHandler application/x-httpd-ea-php74___lsphp .php .php7 .phtml
 </IfModule>
# php -- END cPanel-generated handler, do not edit

## Redirects the index.php file to the root domain
RewriteRule ^index.php$ https://www.digitleseo.com/ [R=301,L]

#redirect  /file.php to /file
RewriteRule ^(.+).php$ /$1 [L,R]
# now we will internally map /file to /file.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)/?$ /$1.php [END]

Answer

This should work for you .

RewriteEngine on
#redirect /?page=foobar.php to /foobar
RewriteCond %{THE_REQUEST} s/(?:index.php)??page=([^.]+).php [NC]
RewriteRule .* /%1? [L,R]
###the rule bellow will internally forward the new URL to the old one
# not an existent file
RewriteCond %{REQUEST_FILENAME} !-f
#not a directory
RewriteCond %{REQUEST_FILENAME} !-d
#rewrite the request /foo/bar to /?page=foo/bar.php
RewriteRule ^(.+)/?$ /?page=$1.php [L,END]