Home  >  Article  >  Backend Development  >  Solution to prohibit direct access of php files under Apache_PHP Tutorial

Solution to prohibit direct access of php files under Apache_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:11:43960browse

At first, I wanted to directly prohibit URLs with php suffix from being accessed in the rewrite rules. But later it was discovered that the rewrite rules are called recursively. If php is directly prohibited in the rewrite rules, the rules rewritten to the php file will also be invalid. RewriteEngineOn

Copy code The code is as follows:

RewriteRule^test$/test.php[L]
RewriteRule^test .php$$0[F,L]
Apache下禁止php文件被直接访问的方法

Recursive calls are really scary. When you first access /test, the URL rewrite is checked once, and then if ^test$ is matched, it will be redirected internally to /test.php. However, the internal redirection will also trigger URL rewriting, so Check again, it matches ^test.php$ and is forced to operate directly [F] (Forbidden), so it becomes a 403 error. In this case, you must determine whether it has 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.

Copy code The code is as follows:

RewriteEngineOn
RewriteRule^test$/test.php[L]
RewriteCond%{REDIRECT_URL}^$

RewriteRule.*$0[F,L] still gets 403 when writing access to /test. After a little inspection, I found that %{REDIRECT_URL} in RewriteCond is always empty, which is really annoying. In this case, it is not included in the rewrite rules. The solution is to ban php directly. But it can be achieved in less flashy ways. Just judge the REDIRECT_URL in the php file. Although this method can be implemented, it feels very inferior, but so far I haven't found any better way.

Copy code The code is as follows:

 $_SERVER['REDIRECT_URL']ordie('Forbidden');
 / /This only displays text. In actual use, the HTTP error code needs to be output.
echo$_SERVER['REDIRECT_URL']; //Successful access display information
?>

If you modify this PHP code and throw it into a global reference, there will basically be no problem. Although it is not a perfect solution, it is at least solved. Maybe you will find a better method in the future.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326799.htmlTechArticleAt first, I wanted to directly prohibit the URL with php suffix from being accessed in the rewrite rules. But later it was discovered that the rewrite rules are called recursively. If php is directly prohibited in the rewrite rules, then rewrite to...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn