htaccess error page file is not working with condition of rewrite

Viewed 32

I have written a condition to auto add the path in the URL and it is working perfectly but now I want to add error pages but it is giving no response instead giving a 500 error. ErrorDocument with text is working fine but it is not adding file I have already checked all possible paths but still no response.

This is my code in .htaccess file.

<IfModule mod_rewrite.c>

        RewriteEngine On

        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ /crud/views/pages/$1 [L]
</IfModule>
ErrorDocument 500 /404.html

ErrorDocument 404 /404.html
1 Answers
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^(.*)$ /crud/views/pages/$1 [L]

This will result in a rewrite loop (500 error) if you request a file (or directory) that does not exist when prefixed with /crud/views/pages/.

Note that defining the 500 ErrorDocument in .htaccess is too late for most 500 errors - this ErrorDocument would need to be defined early in the server config to catch this particular error.

You could resolve this rewrite-loop by first checking that the resource at the desired location exists before rewriting, instead of checking that the current request does not map to a file (or directory). This also involves just one filesystem check rather than two.

For example:

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{DOCUMENT_ROOT}/crud/views/pages/$1 -f
RewriteRule (.*) crud/views/pages/$1 [L]

The first condition that checks against the REDIRECT_STATUS environment variable just makes sure that only direct requests are check and not rewritten requests by the rule itself.

Related