Read Nginx Configuration File Using PHP

This tutorial helps to read configuration file using laravel 7 and PHP 7.You can read Nginx server configuration files by following this tutorial.I ll create Laravel Rest API that will read file and return nginx content.

Nginx is a popular Web server used by many PHP sites.This library provides to create and edit configuration files for Nginx servers.
The nginx configuration file has a .conf extension with the file name.I will use nginx-configurator PHP Library for NGINX configuration parser/generator.

I am using nginx-configurator. This library can parse and generate NGINX configuration files. In the near future will provide CLI commands for NGINX configuration.

How To Install Nginx Configuration

composer require madkom/nginx-configurator

Created Nginx Configuration File

We will read below nginx configuration file, Let’s create nginx.conf file and add below content as follows, We will store this file into laravel /resource/downloads/ folder.

location /laravelenv {
proxy_pass http://localhost:8000/api/v1/hello;
}

Create API Entry into Laravel Routes

I will create routes entry into the routes/api.php file –

Route::resource('read_conf_file', 'EmployeeController@readConfFile');

How To Import NameSpace into Laravel 7

We will import namespace into the controller file at the top position –

use Madkom\NginxConfigurator\Config\Location;
use Madkom\NginxConfigurator\Node\Directive;
use Madkom\NginxConfigurator\Node\Param;

We are using location and directive into the nginx.conf file, So I have imported those classes, You can change as per your requirement.

Method To Read Nginx Configuration

We have created a file and made an entry into an api.php file, Now we will create a method into the EmployeeController.php file.

function getProxyDetails() {
    $parser = new Parser();
    $res = [];
    $configuration = $parser->parseFile(resource_path() . '/downloads/nginx.conf');
    $locations = $configuration->search(function (Location $location) {
        return  $location instanceof Location;
    });
    if (count($locations) > 0) {
        foreach ($locations as $loc) {
            $dircs = $loc->search(function (Directive $dirc)   {
                return $dirc instanceof Directive;
            });
            foreach ($dircs as $dirc) {
                $params = $dirc->getParams();
                array_push($res, $params[0]->getValue());
            }
        }
    }
    return $res;
}

As you can see, I am parsing the file and searching the desired node and directive.We are loading existing Nginx configuration from file or a string, and retrieve and change its values.

Now, We are ready to run our example using below artisan command :

php artisan serve

Let’s open below URL on your browser:

http://localhost:8000/api/v1/read_conf_file

Leave a Reply

Your email address will not be published. Required fields are marked *