我有一个PHP软件,可以用mod_rewrite做漂亮的事情。 但是相同的软件应该在未安装 mod_rewrite 的服务器上运行。 如果安装了 php 代码以及应用了某个规则,我可以签入我的 php 代码mod_rewrite吗?
例如,像这样:
if ((mod_rewrite is enabled) and (mod_rewrite_rule is OK)){
return createBeautifullLink();
}else{
return createUglyLink();
}
提前致谢
使用这个:
在 .htaccess 中
<IfModule mod_rewrite.c>
# inform php that mod_rewrite is enabled
SetEnv HTTP_MOD_REWRITE on
...
在 PHP 中:
$mod_rewrite = FALSE;
if (function_exists("apache_get_modules")) {
$modules = apache_get_modules();
$mod_rewrite = in_array("mod_rewrite",$modules);
}
if (!isset($mod_rewrite) && isset($_SERVER["HTTP_MOD_REWRITE"])) {
$mod_rewrite = ($_SERVER["HTTP_MOD_REWRITE"]=="on" ? TRUE : FALSE);
}
if (!isset($mod_rewrite)) {
// last solution; call a specific page as "mod-rewrite" have been enabled; based on result, we decide.
$result = file_get_contents("http://somepage.com/test_mod_rewrite");
$mod_rewrite = ($result=="ok" ? TRUE : FALSE);
}
第一个(apache)可以由服务器禁用,第二个自定义的只有在安装了mod_env时才以 _SERVER 美元的形式存在。因此,我认为最好的解决方案是在您的 .htaccess 中创建一个虚假的 url 重定向,该重定向指向您的某个文件(仅返回"ok"),并使用来自.php的重定向来调用它;如果返回"确定",则可以使用干净的URL....htaccess 中的重定向代码可能如下所示:
<IfModule mod_rewrite.c>
...
RewriteEngine on
# fake rule to verify if mod rewriting works (if there are unbearable restrictions..)
RewriteRule ^test_mod_rewrite/?$ index.php?type=test_mod_rewrite [NC,L]
(如果 PHP 不在 CGI 中,则以下内容有效)
试试这个:
if (function_exists('apache_get_modules')) {
$modules = apache_get_modules();
$mod_rewrite = in_array('mod_rewrite', $modules);
} else {
$mod_rewrite = getenv('HTTP_MOD_REWRITE')=='On' ? true : false ;
}
或者这个:如何在没有apache_get_modules()的情况下检测mod_rewrite?
致谢归克里斯蒂安·罗伊