loading...

Nginx – Nginx Modules

How to create virtual machines with VirtualBox

Modules are those little pieces of code that give a specific feature or functionality in Nginx. It is because of these modules that you can identify if Nginx is behaving as a web server, reverse proxy server, or a load balancing server. Hence, it is important to understand what modules are and how they formulate the Nginx HTTP request processing structure.

What Are Modules?

The Oxford dictionary defines a module as “any of a number of distinct but interrelated units from which a program may be built up or into which a complex activity may be analyzed.” In simpler words, you can say a module is an independent piece of code that has its own functionality, its own requirement, and its own unique identity that works in conjunction with other pieces of code to build a wholistic structure.

As mentioned earlier, Nginx is modular. It is so much so that right from the initial request, the pieces of code that are executed are all defined in modules. For example, when Nginx is serving you a static index.html file, or when you are requesting for an HTTPS page

, or even when your request is proxied to another server, every function is carried out through various modules. These modules are independent packages or software that are included within the “nginx” binary when you compile Nginx. It is a significant difference between Nginx and Apache, since you cannot dynamically add modules in Nginx. You will need to recompile Nginx to load or unload a particular module.

Note

Apache uses the Dynamic Shared Objects (DSO) concept in which you can load or unload modules at runtime after Apache has been compiled. Using DSO, modules are not included in the main Apache (httpd) process; and hence it allows you to dynamically load or unload modules.

Module Installation

After installing Nginx you can verify which modules are installed on your server using the Nginx -V command. Below you can see the default installation of different modules on CentOS and Ubuntu Server.

Default Installation

The steps for default installation

of Nginx are mentioned in chapter 2’s section “Install Nginx Pre-Built Package.” The next section covers a list of modules that are included during default installation of Nginx.

On CentOS Server

On CentOS you can see that the installation is a clean installation and there are no third-party modules included by default.

$ nginx -V
nginx version: nginx/1.8.0
built by gcc 4.8.2 20140120 (Red Hat 4.8.2-16) (GCC)
built with OpenSSL 1.0.1e-fips 11 Feb 2013
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx
--conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log
--http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid
--lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp
--http-proxy-temp-path=/var/cache/nginx/proxy_temp
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp
--http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx
--with-http_ssl_module --with-http_realip_module --with-http_addition_module
--with-http_sub_module --with-http_dav_module --with-http_flv_module
--with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module
--with-http_random_index_module --with-http_secure_link_module
--with-http_stub_status_module --with-http_auth_request_module --with-mail
--with-mail_ssl_module --with-file-aio --with-ipv6 --with-http_spdy_module
--with-cc-opt='-O2 -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector
--param=ssp-buffer-size=4 -m64 -mtune=generic'
On Ubuntu Server

Ubuntu Server includes few third-party modules in the default installation of Nginx:

$ nginx -V
nginx version: nginx/1.8.0
built with OpenSSL 1.0.1f 6 Jan 2014
TLS SNI support enabled
configure arguments: --with-cc-opt='-g -O2 -fPIE -fstack-protector
--param=ssp-buffer-size=4 -Wformat -Werror=format-security -D_FORTIFY_SOURCE=2'
--with-ld-opt='-Wl,-Bsymbolic-functions -fPIE -pie -Wl,-z,relro -Wl,-z,now'
--prefix=/usr/share/nginx --conf-path=/etc/nginx/nginx.conf
--http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log
--lock-path=/var/lock/nginx.lock --pid-path=/run/nginx.pid
--http-client-body-temp-path=/var/lib/nginx/body
--http-fastcgi-temp-path=/var/lib/nginx/fastcgi
--http-proxy-temp-path=/var/lib/nginx/proxy --http-scgi-temp-path=/var/lib/nginx/scgi
--http-uwsgi-temp-path=/var/lib/nginx/uwsgi --with-debug --with-pcre-jit --with-ipv6
--with-http_ssl_module --with-http_stub_status_module --with-http_realip_module
--with-http_auth_request_module --with-http_addition_module --with-http_dav_module
--with-http_geoip_module --with-http_gunzip_module --with-http_gzip_static_module
--with-http_image_filter_module --with-http_spdy_module --with-http_sub_module
--with-http_xslt_module --with-mail --with-mail_ssl_module
--add-module=/build/buildd/nginx-1.8.0/debian/modules/nginx-auth-pam
--add-module=/build/buildd/nginx-1.8.0/debian/modules/nginx-dav-ext-module
--add-module=/build/buildd/nginx-1.8.0/debian/modules/nginx-echo
--add-module=/build/buildd/nginx-1.8.0/debian/modules/nginx-upstream-fair
--add-module=/build/buildd/nginx-1.8.0/debian/modules/ngx_http_substitutions_filter_module

Module Categories

Nginx modules can be split into five different catagories

based on their functionality. When you build Nginx binary, the Core and Event modules are included by default. The HTTP, Mail, and Stream modules enable Web Server, Mail Proxy, and Reverse Proxy or Load Balancer functionality repectively into Nginx.

Out-of-Box Modules

Nginx source has some modules that are included by default and they can be enabled or disabled during compile time using –with or –without options. The core modules cannot be disabled; they are the required components of Nginx. You can modify the rest of the modules depending on your requirement and functionality expected. There are some OOB modules that have dependencies on third-party components like PCRE, OpenSSL that can be included during compile time. Table 4-1 lists all the different categories of modules and the key modules included in the Nginx source.

Table 4-1. Nginx module types

Module Types

Module Name

Description

Core

ngx_core_module

ngx_error_log_module

ngx_conf_module

This includes modules that enable network and application protocols. It includes modules that handle logging, encryption, etc.

It includes CPU architecture-specific Nginx configuration, it takes care of CPU affinity, thread pool allocation, memory management api, file and sockets IO, etc.

Event

ngx_events_module

ngx_events_core_module

This includes connection processing methods that are event driven. Example connection pooling, etc.

HTTP

ngx_http_module

ngx_http_core_module

ngx_http_log_module

ngx_http_upstream_module

This includes websServer functionality in Nginx and takes care of all HTTP requests.

Mail

ngx_mail_module

ngx_mail_core_module

This includes mail proxy modules.

Stream

ngx_stream_module

ngx_stream_core_module

ngx_stream_proxy_module

ngx_stream_upstream_module

This includes modules that enable proxy, load balance functionality in Nginx.

Third-Party Modules

Third-party or external modules extend Nginx functionality. Nginx has over 100 different third-party modules and the list is growing fast. Nginx has a huge and active community that keeps contributing in extending Nginx. You will look at some of the most popular and highly recommended third-party modules later in the chapter.

How Does a Module Work?

When you run the ./configure script when compiling Nginx, a list of pointers to the Nginx modules are made available. This list of all modules can be found in the ngx_modules.c file in objs directory. It defines the order in which modules are registered: that is, the order in which various handlers are called.

Module Structure

In the simplest form, modules consist of module information, module configuration, handlers, filters, and load balancer functions (refer to Figure 4-1). The module information contains details about the handlers that are provided by the module. The module configuration contains the structure of the module and different commands or directives that are exposed by the module. Handlers consist of the functions that do that actual work on the input and provide the output. Filters contain functions that do different manipulations that are possible on the output of the handler. Load balancer function comes into the picture when different upstream or downstream servers are defined.

Figure 4-1. Nginx Module Structure

How Modules Fit in Nginx

Here are the steps in which a request is processed in Nginx (Figure 4-2 illustrates this graphically):

  1. Start Nginx web server.

  2. Nginx master process gets initiated.

  3. Read nginx.conf.

  4. Creates worker process(es), memory allocation
    , and other architectural specific configuration as per the CPU architecture.

  5. Based on the context like HTTP, MAIL, and STREAM, it creates a list of module handlers and maps them as per their location in the nginx.conf.

  6. If a request is http://​abc.​com, the request is processed in http context.

  7. It will check for the content module handler need to process the request and the respective handler grabs the request and starts working on it.

  8. Once the request is processed, the output is handed over to the filters like gzip, headers, rewrite, etc. The filters will manipulate the output further depending on their order of execution.

  9. If there is any load balancer or proxy module, the respective module will further handle the output.

  10. Finally, the response is sent over to the client.

Figure 4-2. Nginx module process

Configuring Default Modules for Optimal Performance

Now that you know a bit about the internal working of Nginx, it is important to configure modules such that you get optimum performance from your server. You will see some configuration that helps reduce performance overhead on the web server. You will see some of the core, event, and HTTP

modules that are configured on the web servers. Modules are implemented in nginx.conf file in the form of directives or module commands. Some of the directives can be implemented at multiple context and you will find them mentioned along with the commands below.

Core Module

Table 4-2 lists some of the frequently used commands in the core modules. The list describes different directives and its configuration parameter

. The list of core modules lies in the main context ahead of event, HTTP, mail, stream, and other context.

Table 4-2. ngx_core_module directives

Command: user

Syntax

user <username>;

user <username> <groupname>;

Default value

user nobody nobody;

Context

main

Description

This defines the identify under which Nginx process is started. It is recommended to use least privileged user.

Command: worker_processes

Syntax

worker_processes <number>;

worker_processes auto;

Default value

worker_processes = 1;

Context

main

Description

This defines the number of worker processes started by Nginx. It is recommended to set the value to the number of CPU cores on the server. You can also use the value auto, which lets Nginx select an appropriate value. The optimal value depends on multiple factors and you should test the performance impact in your setup before and after making changes.

Command: error_log

Syntax

error_log <path/filename> <level>;

error_log memory:size debug;

Default value

error_log logs/error.log error;

Context

main, http, mail, stream, server, location

Description

This defines the location and level of error logs that are captured. The different levels of error logging are as below (starting from detailed to specific error):

debug: detailed information; used for debugging.

info: information message, lot of details; not very useful.

notice: only notices will be logged; not very useful.

warn: warning messages; indicates some kind of problem.

error: error logs; errors while serving pages.

crit: only critical problem that needs attention.

alert: alert messages of important issues.

emerg: emergency messages when the system is unstable.

Command: pid

Syntax

pid <path/filename>;

Default value

pid logs/nginx.pid;

Context

main

Description

This stores the process ID of the master process. You may think, why save a value of a process identifier in a file?

It serves multiple purposes, especially signaling that the process has at least started successfully. It is also a cheaper way to poll a file in contrast to getting the output of the ps -ax | grep command. However, please be mindful that this approach is not fail-safe. It is possible that the process is dead for long, and the PID file contains stale information.

In general, the PID files are created by daemons that should only be run once on a system. When the process starts, it also creates the lock file. As long as the lock file exists, it won’t start another process. If the lock file exists, but the process id mentioned in the PID file is not running, the daemon can be considered as dead. It may also imply a crash or improper shutdown of the daemon, in which case it might initiate a special startup or restart scenario.

Command: worker_rlimit_nofile

Syntax

worker_rlimit_nofile <number>;

Default value

none

Context

main

Description

This defines the maximum number of open files for the worker processes. You can increase the limit without restarting the main process.

Events Module

Commands in events context

(shown in Table 4-3) determine how Nginx handles connections at a general level. Many times you may not need to configure most of the commands as they are configured by default by Nginx. But you may want to configure a couple of directives for better performance.

Table 4-3. Event module directives

Command: worker_connections

Syntax

worker_connections <number>;

Default value

worker_connections 512;

Context

events

Description

This defines the maximum number of simultaneous connections that can be treated by the worker process. Keep in mind that worker_connections cannot exceed worker_rlimit_nofile if configured.

Command: debug_connections

Syntax

debug_connections <address>;

debug_connections <CIDR>;

Default value

none

Context

events

Description

This defines debug logging for selected client connection. You can specify IPv4 or IPv6 address of a client.

HTTP Module

This context holds configuration parameters for web server that define how Nginx handles HTTP and HTTPS connections (see Table 4-4). This context also includes server context that can occur multiple times as it defines a specific virtual server.

Table 4-4.
HTTP module directives

Command: include

Syntax

include <username>;

include <mask>;

Default value

none

Context

any

Description

This defines including syntactically correct files or mask. Instead of making a long and cluttered nginx.conf file, you can define a virtual server in a specific configuration file and include them directly in the nginx.conf file.

Example:

include conf/mime.types;

include /etc/nginx/proxy.conf;

include vhost/abc.com.conf;

include /etc/nginx/vhosts/*.conf;

Command: default_type

Syntax

default_type <mime.types>;

Default value

default_type text/plain;

Context

http, server, location

Description

This defines the default mime type of a response.

Example:

default_type text/plain;

default_type application/octet-stream;

Command: log_format

Syntax

log_format <name>;

Default value

log_format combined ‘$body_bytes_sent “$http_referer” “$http_user_agent” $remote_addr $remote_user “$request” $time_local $status’;

Context

http

Description

This defines the log format that defines variables that are used only at the time of writing the log. Some of the variables that can be used are as follows:

$body_bytes_sent: number of bytes sent to a client as the response body, this does not include response header.

$http_referer: identifies the URL of the page that is requested.

$http_user_agent: identifies the agent or browser that requested the resource.

$remote_addr: IP address of the client making the request.

$remote_user: Username specified if basic authentication is used.

$request: raw HTTP request URL.

$time_local: local server time that served the request.

$status: A numeric value of the HTTP Statuc Code during the response.

Example:

log_format combined ‘$remote_addr – $remote_user [$time_local] “$request” $status $bytes_sent “$http_referer” “$http_user_agent” “$gzip_ratio”‘;

Command: access_log

Syntax

access_log <path/filename> [format];

access_log off;

Default value

access_log logs/access.log combined;

Context

http, server, location

Description

This defines the path where logs are captured for the requests that are served by the server. When set to off, no logs are captured. The name combined implies the format of the log to be used while logging. In the log_format section previously mentioned you have seen how the log_format is named as combined with appropriate fields.

Command: sendfile

Syntax

sendfile on | off;

Default value

sendfile off;

Context

http, server, location

Description

This defines enabling Nginx to send static content directly from the kernel instead of looking for the resource on disk again. This prevents context switching and enabling a speedy delivery of resources. If you are serving static content, enabling this is essential where as if you are using the server as a reverse proxy this setting does not make any sense.

Command: tcp_nopush

Syntax

tcp_nopush on | off;

Default value

tcp_nopush off;

Context

http, server, location

Description

This enables sending response header and the full file in one packet rather then sending it in chunks. This parameter should be enabled with the sendfile option.

Command: tcp_nodelay

Syntax

tcp_nodelay on | off;

Default value

tcp_nodelay on;

Context

http, server, location

Description

This enables Nginx to send data in chunks, hence avoiding network conjunction. This option is uses keepalive option that allows you to send data without initiating a new connection. This option is the exact opposite of tcp_nopush option you saw earlier.

Command: keepalive_timeout

Syntax

keepalive_timeout <number>;

Default value

keepalive_timeout 75s;

Context

http, server, location

Description

This option sets a timeout value for a connection to stay alive. If you set keepalive_timeout to zero it will disable keep_alive.

Command: listen

Syntax

listen <address>;

listen <ip_address>:<port>;

Default value

listen *:80;

Context

server

Description

This option sets address, IP address, or port on which the server will accept the request. You can use both IP address and port or port or address (i.e., URL or hostname). If you set a default_server with an IP address or address, it will become the default server for the specified address or port.

Example:

listen

www.abc.com

;

listen 127.0.0.1:8080;

listen localhost default_server;

Command: server_name

Syntax

server_name <address>;

server_name *.<address>;

server_name _;

Default value

server_name “”;

Context

server

Description

This option allows you to set the address using either an exact name or wildcard or a hash table to the listen port. Setting up a hash table enables quick processing of static data like server name, MIME types, request header strings, etc. Hash table uses the ngx_http_map module. Using a wildcard enables having multiple URL’s using the same domain name. The catch-all server parameter “_” is used when no valid domain name exists.

Example:

server_name

www.abc.com

one.abc.com;

server_name *.abc.com;

server_name _;

Command: root

Syntax

root <path>;

Default value

root html;

Context

http, server, location

Description

This option specifies the root location of the web content.

Command: error_page

Syntax

error_page code uri;

Default value

none

Context

http, server, location

Description

This option allows you to set the URI for a specific error.

Example:

error_page 403

www.abc.com/forbidden.html

;

error_page 500 501 502 /50x.html;

Command: try_files

Syntax

try_files file uri;

Default value

none

Context

server, location

Description

This option tries to look for the existence of the file specified order or looks at the literal path you specified in the root directive and sets the internal file pointer. In the below example, when a request is made a try_files directive will look for index.html, index.php in the /website/root_directory. If it fails to find it, it will look into the $document_root directory specified at the root directive and serve the request.

Example:

try_files /website/root_directory/ $uri;

Enabling Optional Modules

There are number of other modules that can be enabled and they have their own directives. You will see in this section how to enable gzip, FastCGI, and Basic Auth directives. These are optional and need not exist on all servers.

Gzip Module

The gzip modules

help in compressing the responses. Table 4-5 lists the directives.

Table 4-5. Gzip directives

Command: gzip

Syntax

gzip on | off;

Default value

gzip off;

Context

HTTP, server, location

Description

This defines if Nginx will compress the responses.

Command: gzip_comp_level

Syntax

gzip_comp_level <level>;

Default value

gzip_comp_level 1;

Context

HTTP, server, location

Description

This defines how compressed the response should be on a scale of 1 to 9 where 9 is the most compressed. The higher the compression level the longer it takes to compress and decompress the data. Setting a higher compression level can actually result in slow performance on a website with high volume.

Command: gzip_types

Syntax

gzip_types <mime.type>;

Default value

gzip_types text/html;

Context

HTTP, server, location

Description

This option enables compressing content with the specified mime type. It is very helpful to filter down the type of files that should be compressed. For example, it makes a lot of sense to compress files that are of type text (like JavaScript, CSS, html, etc.), but it doesn’t usually help compressing a JPG or MPEG file. On the contrary, trying to compress an already compressed file ends up wasting CPU cycles, and often results in poor performance of a web server.

FastCGI Module

This module allows passing the requests to a FastCGI server

for further processing. Table 4-6 shows the basic semantics of this directive.

Table 4-6. FastCGI directives

Command: fastcgi_pass

Syntax

fastcgi_pass <address>;

Default value

none

Context

location

Description

This option enables address of FastCGI server. The address can be a URI or Unix socket. Nginx is not capable of handling CGI requests itself, so it hands it over to components that are better suited for the job. Typically, a web application like WordPress that uses PHP is configured using fastcgi.

Example:

fastcgi_pass
http://localhost:9000
;

fastcgi_pass unix:/fastcgi.socket;

Command: fastcgi_index

Syntax

fastcgi_index <name>;

Default value

none

Context

http, server, location

Description

This option sets a file name that will be appended after a URI.

Example:

fastcgi_index index.php;

Command: fastcgi_split_path_info

Syntax

fastcgi_split_path_info <regex>;

Default value

none

Context

location

Description

This option defines a regular expression that captures a value of the FastCGI path.

Example:

fastcgi_split_path_info ^(.+\.php)(/.+)$;

Command: fastcgi_param

Syntax

fastcgi_param <parameter> <value>;

Default value

none

Context

location

Description

This option sets a parameter that should be passed to the FastCGI server. The value can contain text, variables, and other combinations.

Example:

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

Basic Authentication

This directive enables authentication

by the web server using the basic authentication technique, which is a cleartext (Base 64 encoded) way of authenticating a client. Table 4-7 shows the details.

Table 4-7. Basic Authentication directives

Command: auth_basic

Syntax

auth_basic <string> | off;

Default value

auth_basic off;

Context

http, server, location

Description

This enables validation of users’ credentials using basic authentication protocol. When set to off, your website will be accessible to everyone without any authentication taking place.

Command: auth_basic_user_file

Syntax

auth_basic_user_file <file>;

Default value

none

Context

http, server, location

Description

This option uses a file that will keep username and password of the users that will be allowed access to website with basic auth enabled.

The file should be in the following format:

username1:password1

username2:password2:comment

username3:password3

Enabling Third-Party Modules

There are various sources on the Internet from where you can to get third-party Nginx modules. You can look for modules at the official Nginx website
https://www.nginx.com/resources/wiki/modules/
. Extending your server purely depends on the kind of services you are expecting off your Nginx server. There is no recommended or standard process you need to follow to install modules and use them. You will find most of the modules include README file that will guide you on the steps required to install the module.

Before you extend Nginx with any third-party module, you need to know about its dependencies. You will see an example of installing and implementing PAM Authentication Module on the server. The idea here is to show how you can identify and address dependencies of a module.

PAM Authentication

Let’s assume that Basic Authentication module doesn’t suit your requirement as well as you would have liked, and you want something more robust.

In such scenarios, it would be a pain to develop a module of your own. Thankfully, there is a module that is a great alternative for implementing a flexible authentication mechanism on your website. PAM is used for implementing various authentication methods like User, LDAP, SQL, and SSO-based authentication. You will see how to implement PAM Auth for non-root users on the server.

Compiling the Module with Nginx

Here are the steps you need to follow:

  1. Begin by downloading the module from the author’s Github repository. Download the latest version of the module; as of this writing the module version is 1.4.

    # wget https://github.com/stogh/ngx_http_auth_pam_module/archive/v1.4.tar.gz
  2. Extract the files:

    # tar xzvf v1.4.tar.gz
    ngx_http_auth_pam_module-1.4/
    ngx_http_auth_pam_module-1.4/ChangeLog
    ngx_http_auth_pam_module-1.4/LICENSE
    ngx_http_auth_pam_module-1.4/README.md
    ngx_http_auth_pam_module-1.4/config
    ngx_http_auth_pam_module-1.4/ngx_http_auth_pam_module.c

    As you can see, the module contains a README.md file that contains all the instruction for installing and configuring the module. The only file that is the core of the module is the C source file (ngx_http_auth_pam_module.c).

  3. Open the scripted file that we used in chapter 2 and add the lines below at the bottom of the file.

    --add-module=/home/username/ngx_http_auth_pam_module-1.4
  4. Execute the file using ./scripted command.

  5. The configure output will have an output like shown below:

    ...
    configuring additional modules
    adding module in /home/username/ngx_http_auth_pam_module-1.4
     + ngx_http_auth_pam_module was configured
    ...
  6. Run the make command.

    Below is an example of missing dependency while actual compiling the module. In this case, your server is missing the PAM development package on the server:

    /home/username/ngx_http_auth_pam_module-1.4/ngx_http_auth_pam_module.c:13:31: fatal error: security/pam_appl.h: No such file or directory
     #include <security/pam_appl.h>
                                   ^
    compilation terminated.
    make[1]: *** [objs/addon/ngx_http_auth_pam_module-1.4/ngx_http_auth_pam_module.o] Error 1
    make[1]: Leaving directory `/home/username/nginx-1.8.0'
    make: *** [build] Error 2
  7. To eliminate the error, you will need to install PAM module on Ubuntu Server; here is the command

    sudo apt-get install libpam-dev (or yum install pam-devel on CentOS)
  8. Run make command. This time the module is able to find the required component on the server and compilation is successful.

  9. Run the sudo make install command.

  10. Just to be sure, restart Nginx service and ensure the website is working as expected:

    # service nginx start

Verifying Installation

Once you are done installing Nginx, you can verify the module installation

. This shows you all the modules that are included during your scripted installation:

nginx version: nginx/1.8.0
built by gcc 4.8.4 (Ubuntu 4.8.4-2ubuntu1∼14.04)
built with OpenSSL 1.0.1f 6 Jan 2014
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx
--conf-path=/etc/nginx/nginx.conf --pid-path=/var/run/nginx.pid
--lock-path=/var/run/nginx.lock --error-log-path=/var/log/nginx/error.log
--http-log-path=/var/log/nginx/access.log
--http-client-body-temp-path=/var/cache/client_body_temp
--http-fastcgi-temp-path=/var/cache/fastcgi_temp
--with-http_gzip_static_module --with-http_stub_status_module --with-http_ssl_module
--with-pcre --with-file-aio --with-http_realip_module --without-http_scgi_module
--without-http_uwsgi_module --without-http_proxy_module --user=nginx --group=nginx
--add-module=/home/johndoe/ngx_http_auth_pam_module-1.4

Implementing the Module in Nginx

Now that the module is compiled in, follow these steps to configure it:

  1. PAM includes two directives auth_pam and auth_pam_service_name. To implement PAM Auth with Nginx you will need to edit the nginx.conf file. You can insert the below two lines under the location directive as shown below:

            location / {
                root   html;
                index  index.html index.htm;
                auth_pam     "Authentication Required...";
                auth_pam_service_name "nginx";
  2. You will need to reload nginx configuration after the changes are saved:

    sudo nginx –s reload
  3. PAM uses pam_unix.so file for authentication and will be authenticating local users on the server. You need to ensure the Nginx worker process has read access to the /etc/shadow file. You can achieve this by adding the account to the “ shadow” group, which is the default group for /etc/shadow file. The command to achieve the same is below:

    sudo usermod -a -G shadow nginx

Validating the Module

You are almost set. To vali

date, do what follows:

  1. You can now validate if the module is able to authenticate the user. You can use a Chrome extension called Postman.

  2. Figure 4-3 shows request status without entering any credentials.

    Figure 4-3. Nginx requesting valid credentials
  3. Now, after you enter a valid username and credential

    , as shown in Figure 4-4, the request is processed successfully.

    Figure 4-4. Nginx processes the request with valid credentials
Note

In CentOS 7 “ shadow” group is missing and for security reasons /etc/shadow file does not have access to anybody except root. It is recommended that you do not fiddle around with “ shadow” file. It is a very sensitive file and has passwords of local users, which are stored in encrypted format.

Summary

In this chapter you have learned about the modules in Nginx and how they define the core purpose of the web server. You should now be comfortable with setting up your server with custom modules based on your needs. You have also learned about the different categories of modules, and how it gets hooked in the request processing pipeline.

Nginx has good support for pluggable modules, and it is in your best interest to check them out regularly so that you don’t end up reinventing the wheel by creating something that is is already present.

Comments are closed.

loading...