Htaccess: How to redirect to 404 if url parameter is missing or invalid

.htaccessredirect

Assume the following folder structure on the webserver (Apache):
https://somedomain.com/parentfolder/childfolder.

Using .htaccess, I'd like to display the childfolder and any of it's children (files as well as folders) only the URL contains a certain parameter. For example, the page should be shown if it's requested by:

https://somedomain.com/parentfolder/childfolder?secretparameter=secretvalue123

However if

  • the value of parameter secretparameter is not exactly secretvalue123 or
  • the parameter secretparameter is missing,

then a 404 error should be returned.

Do you have any ideas how the .htaccess rules would look like to accomplish this? Your help is greatly appreciated, thank you.

Best Answer

So, if the query string is not secretparameter=secretvalue123 when requesting a resource within the childfolder then issue a 404 not found. You can do something like the following at the top of the .htaccess file in the document root using mod_rewrite:

RewriteEngine On
RewriteCond %{QUERY_STRING} !=secretparameter=secretvalue123
RewriteRule ^parentfolder/childfolder - [R=404]

This blocks the request if the query string is not exactly equal to secretparameter=secretvalue123. (You don't need the L flag here when specifying a non-3xx code as it is implied.)

You could simplify the RewriteRule slightly if instead, you placed these directives in the subdirectory you want to protect. ie. at /parentfolder/childfolder/.htaccess. For example:

RewriteRule ^ - [R=404]