0

i'm getting a little bit frustrated, so any help would be appreciated. Is it possible to catch a 404/directory not found, combined with a FilesMatch-block in .htaccess?

I created the following .htacces in order to rewrite non existing .json-files to a 204 No Content (preventing errors when using $.getJSON):

<FilesMatch "\.(json)$">

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f [OR]
    RewriteCond %{REQUEST_FILENAME} !-d [OR]
    RewriteCond %{REQUEST_FILENAME} !-l
    RewriteRule ^ - [R=204]

</FilesMatch>

I tested some things with the following files/directories-structure:

httpdocs
 - a
  - a.json
 - b

The .htaccess works when I request a non-existing configuration-file (b/b.json), but when I try to load a configuration-file of a non-existing directory (c/c.json), a 404 statusCode will be returned instead of the desired 204.

Requesting a/a.json gives httpStatusCode 200 (Found, which is correct)

Requesting b/b.json gives httpStatusCode 204 (No content, also correct, handled by the .htaccess)

Requesting c/c.json gives httpStatusCode 404 (Not Found)

I want request c to return a 204 No Content as well. I've tried some thing like catching the directory from the request using <FilesMatch .*\/(.*)\.(json)$> and using the $1 for the -d instead of the %{REQUEST_FILENAME}, but this doesn't work.

I also tried to catch the 404-error using the ErrorDocument, only for .json-files, but this doesn't seam to work. The redirect won't work and a 404 statusCode will be returned.

<FilesMatch "\.(json)$">

    ErrorDocument 404 /204.php

</FilesMatch>

What am I doing wrong? Any ideas how to catch this?

Bazardshoxer
  • 545
  • 1
  • 5
  • 22
  • 1
    Why use `FilesMatch` at all, just specify what URL format you want to match directly in the RewriteRule. – CBroe Aug 07 '20 at 09:35
  • 1
    Remove `FilesMatch`, make the rule `RewriteRule \.json$ - [R=204]` instead, and you should be good. – CBroe Aug 07 '20 at 09:35
  • Ah, nice. Don't know exactly why I was stuck to using FilesMatch, but removing it solves everything, thanks a lot @CBroe! – Bazardshoxer Aug 07 '20 at 10:04

1 Answers1

1

No need to use FilesMatch here, you can simply limit what URLs this applies to directly in the RweriteRule itself.

RewriteRule \.json$ - [R=204]
CBroe
  • 91,630
  • 14
  • 92
  • 150