重定向非现有子文件夹,但如果URL包含关键字,则允许

I have read lots of threads about htaccess redirect, but none really match my situation, albeit quite simple, got me pulling my hair out.

for example I have a site with this structure:

 root
 -gallery.php

And I have already implement htaccess rule to hide .php extension. How do I catch the following events:

  1. mysite.com/nonexistingfolder would go to mysite.com/404.php
  2. mysite.com/gallery/nonexistingfolder would still load mysite.com/gallery, so that I can catch the /nonexistingfolder as a $_GET inside mysite.com/gallery.php?

Append this after RewriteRule

ErrorDocument 404 /error_docs/404

Replace /error_docs/404 with the file that shows the error or does something.

For the regular 404 page, use an error document:

ErrorDocument 404 /404.php

That covers #1, non-existing folder will go there.

For #2 try:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^gallery/(\w+)$ /gallery.php?page=$1 [L]