How can I return 404 for specified existing file in apache and nginx?

Solution 1:

NGINX:

location = /config.php {
    return 404;
}

Solution 2:

You don't need .htaccess with Apache, and it's actually only recommended as a last resort. Likewise, mod_rewrite should only be used if necessary: When not to use mod_rewrite.

You can use both Redirect and RedirectMatch from mod_alias to return 404:

  • Redirect 404 /config.php
  • RedirectMatch 404 ^/config.php$

You can place them directly in your server configuration, or in your Virtual Host, e.g.

<VirtualHost *:80> 
    ServerName www.example.com
    DocumentRoot "/var/www/example.com"

    Redirect 404 /config.php
</VirtualHost>

Solution 3:

.htaccess on Apache (using mod_rewrite):

RewriteEngine On

RewriteRule ^config\.php$ - [R=404]

Assuming /config.php in the document root.