I'm trying my hands on writing a simple REST API and am currently trying to properly configure my .htaccess
file.
What I'd like to achieve is the following:
- have
RewriteRule
s to direct requests towards the actual RestController - catch all requests not explicitly served with a
RewriteRule
before with a FITTING error- requests that target any file, subdirectory or file in subdirectory not handled with a former
RewriteRule
should be answered403
- requests that target any non-existent file or subdirectory should be answered
404
- requests that target any file, subdirectory or file in subdirectory not handled with a former
What I have achieved up until now is:
- ✅ serving non-existent files, subdirs and files in subdirs
404
- ✅ serving existing files and subdirs without proper
RewriteRule
403
- ❌ forwarding valid API requests to the proper endpoint (it stopped working after I added the last
403
rule) - ❌ serving
403
for existing files IN SUBDIRS without properRewriteRule
- eg. when I try to accessdomain.com/subdir/existingfile.pdf
, it actually shows the file, which I don't want.
Since subdirs may be created dynamically, I want ALL subdirs and files in them to be handled 403 without having to manually specify them.
This is my current .htaccess
:
Options -Indexes
RewriteEngine on
RewriteRule ^ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# REST mappings
RewriteRule ^json$ RestController.php?key=json [L,nc,qsa]
RewriteRule ^file/(.*)$ RestController.php?key=file&id=$1 [L,nc,qsa]
RewriteRule ^actions$ RestController.php?key=actions&id=none [L,nc,qsa]
RewriteRule ^actions/(.*)$ RestController.php?key=actions&id=$1 [L,nc,qsa]
# catch all non-matched requests and throw 404 or 403 accordingly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ - [R=404,NC,L]
RewriteRule ^ - [R=403,NC,L]