从PHP中读取mod_rewrite配置

JDC*_*JDC 0 php apache mod-rewrite

我有一个PHP软件,用mod_rewrite做漂亮的事情.但是相同的软件应该在没有安装mod_rewrite的服务器上运行.如果安装了mod_rewrite并且是否应用了某个规则,我可以检查我的php代码吗?

例如,像这样:

    if ((mod_rewrite is enabled) and (mod_rewrite_rule is OK)){
        return  createBeautifullLink();
    }else{
        return createUglyLink();
    }
Run Code Online (Sandbox Code Playgroud)

提前致谢

小智 7

用这个:

.htaccess

<IfModule mod_rewrite.c>
   # inform php that mod_rewrite is enabled
   SetEnv HTTP_MOD_REWRITE on
   ...
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

第一个(apache)可以被服务器禁用,第二个自定义的只有在安装了mod_env时才会存在于$ _SERVER中.所以我认为最好的解决方案是在你的.htaccess中创建一个虚假的 URL重定向,指向你的某个文件(只返回"ok"),然后从.php重定向调用它.如果返回"ok",则可以使用干净的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]
Run Code Online (Sandbox Code Playgroud)