Home  >  Article  >  Backend Development  >  What should I do if direct access to php files under Apache is prohibited?

What should I do if direct access to php files under Apache is prohibited?

coldplay.xixi
coldplay.xixiOriginal
2020-09-07 11:48:162717browse

Apache下php文件被禁止直接访问的解决办法:直接在php文件中判断【REDIRECT_URL】即可,代码为【$_SERVER['REDIRECT_URL']ordie('Forbidden')】。

What should I do if direct access to php files under Apache is prohibited?

【相关学习推荐:php视频教程(视频)】

Apache下禁止php文件被直接访问的解决办法:

一开始,我想在重写规则里直接禁止php后缀的URL被访问。但后来发现重写规则是递归调用的,如果在重写规则里直接禁止php,那么重写到php文件的规则也会失效。RewriteEngineOn

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

What should I do if direct access to php files under Apache is prohibited?

递归调用这真可怕,一开始访问/test的时候URL重写检查一次,然后匹配到^test$就内部重定向到/test.php,然而内部重定向也会触发URL重写,因此再次检查,匹配到^test.php$,被强制直接[F](Forbidden)操作,所以就变成了403错误。既然这样,就必须判是否已经经过服务器重定向。这时候服务器变量里有个REDIRECT_URL可以使用,因此我试着用这个做判断。

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

RewriteRule.*$0[F,L]这样写访问/test依旧被403,稍微检查下,发现RewriteCond中%{REDIRECT_URL}永远为空,这样的话在重写规则中没办法直接禁止php了。

但是可以用不怎么华丽的方法实现。就是在php文件中去判断REDIRECT_URL,虽然这个方法可以实现,但是感觉很逊,只是目前为止也没找到什么更好的办法了。

  $_SERVER['REDIRECT_URL']ordie('Forbidden');
  //这里只是显示文字而已,实际使用的时候还需输出的HTTP错误代码。
  echo$_SERVER['REDIRECT_URL'];//成功访问显示信息
  ?>

把这段PHP代码修改下丢进全局引用里就基本上没啥问题了,虽然不是完美解决,但是至少还是解决了,以后也许会发现更好的方法。

What should I do if direct access to php files under Apache is prohibited?

想了解更多编程学习,敬请关注php培训栏目!

The above is the detailed content of What should I do if direct access to php files under Apache is prohibited?. For more information, please follow other related articles on the PHP Chinese website!

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