Apache bans php files from being accessed directly

  
                  

In the beginning, I wanted to disable the URL of the php suffix directly from being accessed in the rewrite rules. But later found that the rewrite rules are recursively called. If php is directly disabled in the rewrite rules, the rules for rewriting to the php file will also be invalid. RewriteEngineOn

RewriteRule^test$/test.php[L]

RewriteRule^test.php$$0[F,L]

Recursive call This is terrible, at the beginning The URL rewrite is checked once when accessing /test, and then it is internally redirected to /test.php when it matches ^test$. However, internal redirection also triggers URL rewriting, so check again and match to ^test.php$. It was forced to operate directly [F] (Forbidden), so it became a 403 error. In this case, you must determine whether you have been redirected by the server. At this time there is a REDIRECT_URL in the server variable that can be used, so I tried to use this to make a judgment.

RewriteEngineOn

RewriteRule^test$/test.php[L]

RewriteCond%{REDIRECT_URL}^$

RewriteRule.*$0[F, L] This write access /test is still 403, a little check, found that RewriteCond %{REDIRECT_URL} is always empty, this is a pain, so there is no way to directly ban php in the rewrite rules. But it can be done in a less expensive way. It is to judge REDIRECT_URL in the php file. Although this method can be implemented, it feels very inferior, but it has not found any better way so far.

$_SERVER['REDIRECT_URL']ordie('Forbidden');

//This is just a display of the text, and the HTTP error code to be output when actually used.

echo$_SERVER['REDIRECT_URL'];//Successfully access the display information

?>

Put this PHP code into the global reference and modify it. There is no problem with it. Although it is not a perfect solution, it is at least solved. In the future, you may find a better way.

Copyright © Windows knowledge All Rights Reserved