I am trying to display custom 404 page for the documents or folder or file or link which may or may not exist but i still want to show a message of 404 to visitor for some purpose.
I have checked Setting a custom 404 page for a specific URL in htaccess and Setting a custom 404 page for a specific URL in htaccess
Code :
RewriteRule ^foo.html$ /spoof404.txt [L,R=404,NC]
RewriteRule ^hello$ /spoof404.txt [L,R=404,NC]
RewriteRule ^file/example.php$ /spoof404.txt [L,R=404,NC]
With these code, i am successfully getting 404 Status in header
but it not displaying the contents of spoof404.txt
Note:
I am not looking for Errordocument like 404 or 403
Why not? That is exactly how you do this. There is no other way on Apache-only (without using another server-side script) to trigger a 404 HTTP status and serve a custom response.
For example:
ErrorDocument 404 /spoof404.txt
RewriteRule ^foo\.html$ - [NC,R=404]
RewriteRule ^hello$ - [NC,R=404]
RewriteRule ^file/example\.php$ - [NC,R=404]
When you request /foo.html
it will trigger a 404 and /spoof404.txt
will be served.
When specifying a status ode outside of the 3xx range, the substituion string is ignored (hence the use of a single -
- hyphen). In this case, the L
flag is also superfluous, since it is implied when specifying a non-3xx R
code.
UPDATE:
how to block with parameters like
example.com/something.php?something=tokens&othertoken=token
The RewriteRule
directive matches against the URL-path only, to match the query string (everything after the first ?
) then you need an additional condition (RewriteCond
directive) and check against the QUERY_STRING
server variable.
For example, to match that exact URL (although case-insensitively) and trigger a 404:
RewriteCond %{QUERY_STRING} ^something=tokens&othertoken=token$ [NC]
RewriteRule ^something\.php$ - [NC,R=404]