0

我用下面的 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 做到这一点,最好的解决方案是什么?

4

1 回答 1

1

您可以通过将 php 文件放在公共文件夹之外来实现您想要的,而不是让您的 index.php 文件包含它们

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

在 index.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 扩展名,但这与您的主机有关,还是与旧要求有关?因为使用 htaccess,您可以拥有干净的网址,例如

mydomain.com/products/widget/

于 2012-12-08T14:53:56.060 回答