How to Check if mod_rewrite is Enabled on Server in PHP?

Problem:

May be you’re going to rewrite the URLs of your webpages (to make URLs more SEO friendly) which requires mod_rewrite module to be enabled in the apache server. Before writing any code for this, you want to make sure that the mod_rewrite module is enabled.

Solution:

You can check it in few ways. Here you’ll see two methods-

Method 1: Using phpinfo() function

phpinfo() function displays information about your PHP-configuration. Just run the following code in your web server.

<?php
    phpinfo();
?>

The above code will display lots of information including whether mod_rewrite module has been enabled or not. Search (CTL+f) with the string “mod_rewrite” in this page. If it is enabled, you’ll see it in “Loaded Modules” section, like the picture below-

How to Check if mod rewrite is Enabled in PHP

Method 2: Using apache_get_modules() function

apache_get_modules() function displays a list of modules that are enabled in your PHP configuration. If mod_rewrite module is enabled, it will also be included on that list. Run the following code –

<pre>
<?php
    $modules = apache_get_modules();
    echo in_array('mod_rewrite', $modules) ? "mod_rewrite module is enabled" : "mod_rewrite module is not enabled";
?>
</pre>

Output:
If mod_rewrite module is enabled, you’ll see the output: “mod_rewrite module is enabled”.
If mod_rewrite module is not enabled, you’ll see the output: “mod_rewrite module is not enabled”.

How it works:
apache_get_modules() function returns an array which contains all the modules that are enabled. Each element in the array is a module. So, we check whether mod_rewrite is an element of that array using the in_array() function.