阻止直接访问PHP文件

时间:2012-01-11 08:53:05

标签: php mod-rewrite

我现在的htaccess文件包含执行此操作的mod_rewrite规则:

www.mysite.com/articles/jkr/harrypotter --> www.mysite.com/index.php?p=articles&author=jkr&book=harrypotter

www.mysite.com/articles/jkr --> www.mysite.com/index.php?p=articles&author=jkr

www.mysite.com/articles --> www.mysite.com/index.php?p=articles

在我的根目录中,我有一些PHP文件,如:index.php,pre.php,view.php等。

我想要的:阻止直接访问php文件。

例如:

www.mysite.com/index.php --> "404 - Page Not Found" or "File not exist"

www.mysite.com/view.php --> "404 - Page Not Found" or "File not exist"

我尝试过在搜索时找到的代码。它使用“f”标志。但我不明白。当我使用它时也不显示主页。所以,我删除了我正在测试的所有内容。我的htaccess文件现在只包含三个规则(接受页面,作者,书籍)。

请帮忙。

3 个答案:

答案 0 :(得分:2)

我在此处看到了另一个问题:mod_rewrite error 404 if .php

我对它做了一个更改,添加了[NC]标志。否则,如果我们将大写字母放在扩展名中(例如“index.PHP”),它将加载。

所以, 的解决方案:

RewriteCond %{THE_REQUEST} \.php[\ /?].*HTTP/ [NC]
RewriteRule ^.*$ - [R=404,L]

谢谢

答案 1 :(得分:0)

创建一个抛出404错误的简单404.php,然后将index.php重写为404.php等。

答案 2 :(得分:0)

您也可以在脚本级别执行此操作。如果你在index.php中添加一个规则来检查你是否已经传递了GET变量,或者只是调用了没有任何参数的页面:

<?

    if(empty($_GET)) 
        header('Location: http://www.yoursite.com/404.php');
    else 
       //your usual script

?>

然后您可以控制将人们重定向到404错误或显示更有帮助的内容,例如带有索引或某种形式的网站导航的着陆页。