使用 htaccess 将 PHP 文件名重写为 cgi,并拒绝访问 php 文件



我用下面的htaccess代码重写php文件的文件名:

ErrorDocument 404 /notfound.html
AddType application/x-httpd-php .cgi
RewriteEngine on 
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|%3D) [OR]
RewriteCond %{QUERY_STRING} base64_encode[^(]*([^)]*) [OR]
RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2})
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [F,L]
RewriteRule ^(.*).cgi $1.php 

我想做什么:我也可以限制对php文件的访问吗? 例如,如果访问者想看page.php得到404错误,什么时候想看main.cgi页面可以看到页面没有错误,可以吗?
如果我不能仅使用 htaccess 来做到这一点,最好的解决方案是什么?

你可以通过将

php 文件放在公共文件夹之外来实现你想要的,而不是让你的索引.php文件包含它们

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [F,L]

在索引中.php类似

$validFiles = array('page', 'about', 'gallery');
$requestedFile = str_replace('.cgi', '', trim($_SERVER['REQUEST_URI'], '/');
if(in_array($requestedFile, $validFiles ))
{
    // ../ goes into the parent folder, and code is a sibling of your public folder
    include '../code/'.$requestedFile.'.php';
}
else
{
    // file not found stuff or index here
}

虽然我会质疑为什么你需要使用 .cgi 扩展,但这与您的主机有关,还是遗留要求? 因为使用 HTeAccess,您可以拥有干净的网址,例如

mydomain.com/products/widget/

最新更新