My question is somewhat similar to this one but not exactly and I can't understand it enough to adapt it to my needs.
I have this htaccess rule to remove file extensions which works well
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^\.] )$ $1.php [NC,L]
So /somepage
refers to /somepage.php
. I now need a sort of fallback to it incase somepage.php
doesn't exist.
In which case /somepage
would rewrite to /catchall.php?link=somepage
which can handle the requests. How can I do this?
CodePudding user response:
Your current rule is adding .php
extension blindly without checking existence of matching .php
file. You can tweak your rule to check for presence of .php
file and then only add .php
. When a matching .php
file doesn't exist then we can rewrite to /catchall.php
.
RewriteEngine On
# add .php extension only if a matching .php file exists
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(. ?)/?$ $1.php [L]
# If URI is still not pointing to a valid file/directory
# then rewrite to /catchall.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . catchall.php?link=$0 [L,QSA]