Automatic check if mod_rewrite rules are enabled

Sometimes there is a need to check if mod_rewrite rules are enabled or not from a server script and in this post, I will show a method of automatic detection that we use.

To pass all user requests to front-page controller in Modera products we use the following rules:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME}  !-d #exclude requests to real directories
RewriteCond %{REQUEST_FILENAME}  !-f #exclude request to real files
RewriteRule .+ index.php [L]

For checking if these rules are active we are making HTTP request to predefined URI, which in case of enabled rules will be handled by front-page controller script index.php which will reply with predefined response, if rules are not enabled then this server will return back with a 404 HTTP response.

Here is the proof-of-concept PHP script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
$test_uri = '/60cae09d692ab797c6093756f847442b';
 
// check for test uri
if ($_SERVER["REQUEST_URI"] == $test_uri) {
    header("HTTP/1.0 202 Accepted");
    exit();
}
 
// make test connection back to server
$fp = fsockopen($_SERVER["SERVER_ADDR"], $_SERVER["SERVER_PORT"]);
if ($fp) {
    socket_set_timeout($fp, 5);
    fputs($fp, "HEAD $test_uri HTTP/1.0\r\n");
    fputs($fp, "Host: $_SERVER[SERVER_NAME]\r\n\r\n");
    $response = fgets($fp);
    fclose($fp);
 
    // check for predefined response
    if (strpos($response, " 202")) {
        echo "mod_rewrite rules are enabled";
    } else {
        echo "mod_rewrite rules are not enabled";
    }
 
} else {
    echo "Unable to make connection";
}

Leave a Reply