Tag Archives: Nginx reverse proxy

a2ensite a2dissite for NGINX

Using a2ensite and a2dissite command for NGINX

a2ensite a2dissite for NGINX

As we all know, we can enable or disable a website using Apache on Debian and Ubuntu Linux. I’m pretty sure we remembered and appreciated using the a2ensite and a2dissite commands, why not for NGINX!

Unfortunately, there is no corresponding standard command in NGINX, but there is a workaround using a2ensite and a2dissite for NGINX.

Of course, the following command can create the symlink to the website configuration file:

$ ln -s /etc/nginx/sites-available/example.org /etc/nginx/sites-enabled/

a2ensite and a2dissite command for NGINX

The following shell script can be used to activate and deactivate websites and also list them.

Much easier to use nginx_modsite

Just create this script /usr/bin/nginx_modsite.

#!/bin/bash

##
#  File:
#    nginx_modsite
#  Description:
#    Provides a basic script to automate enabling and disabling websites found
#    in the default configuration directories:
#      /etc/nginx/sites-available and /etc/nginx/sites-enabled
#    For easy access to this script, copy it into the directory:
#      /usr/local/sbin
#    Run this script without any arguments or with -h or --help to see a basic
#    help dialog displaying all options.
##

# Copyright (C) 2010 Michael Lustfield <mtecknology@ubuntu.com>

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

##
# Default Settings
##

NGINX_CONF_FILE="$(awk -F= -v RS=' ' '/conf-path/ {print $2}' <<< $(nginx -V 2>&1))"
NGINX_CONF_DIR="${NGINX_CONF_FILE%/*}"
NGINX_SITES_AVAILABLE="$NGINX_CONF_DIR/sites-available"
NGINX_SITES_ENABLED="$NGINX_CONF_DIR/sites-enabled"
SELECTED_SITE="$2"

##
# Script Functions
##

ngx_enable_site() {
    [[ ! "$SELECTED_SITE" ]] &&
        ngx_select_site "not_enabled"

    [[ ! -e "$NGINX_SITES_AVAILABLE/$SELECTED_SITE" ]] && 
        ngx_error "Site does not appear to exist."
    [[ -e "$NGINX_SITES_ENABLED/$SELECTED_SITE" ]] &&
        ngx_error "Site appears to already be enabled"

    ln -sf "$NGINX_SITES_AVAILABLE/$SELECTED_SITE" -T "$NGINX_SITES_ENABLED/$SELECTED_SITE"
    ngx_reload
}

ngx_disable_site() {
    [[ ! "$SELECTED_SITE" ]] &&
        ngx_select_site "is_enabled"

    [[ ! -e "$NGINX_SITES_AVAILABLE/$SELECTED_SITE" ]] &&
        ngx_error "Site does not appear to be \'available\'. - Not Removing"
    [[ ! -e "$NGINX_SITES_ENABLED/$SELECTED_SITE" ]] &&
        ngx_error "Site does not appear to be enabled."

    rm -f "$NGINX_SITES_ENABLED/$SELECTED_SITE"
    ngx_reload
}

ngx_list_site() {
    echo "Available sites:"
    ngx_sites "available"
    echo "Enabled Sites"
    ngx_sites "enabled"
}

##
# Helper Functions
##

ngx_select_site() {
    sites_avail=($NGINX_SITES_AVAILABLE/*)
    sa="${sites_avail[@]##*/}"
    sites_en=($NGINX_SITES_ENABLED/*)
    se="${sites_en[@]##*/}"

    case "$1" in
        not_enabled) sites=$(comm -13 <(printf "%s\n" $se) <(printf "%s\n" $sa));;
        is_enabled) sites=$(comm -12 <(printf "%s\n" $se) <(printf "%s\n" $sa));;
    esac

    ngx_prompt "$sites"
}

ngx_prompt() {
    sites=($1)
    i=0

    echo "SELECT A WEBSITE:"
    for site in ${sites[@]}; do
        echo -e "$i:\t${sites[$i]}"
        ((i++))
    done

    read -p "Enter number for website: " i
    SELECTED_SITE="${sites[$i]}"
}

ngx_sites() {
    case "$1" in
        available) dir="$NGINX_SITES_AVAILABLE";;
        enabled) dir="$NGINX_SITES_ENABLED";;
    esac

    for file in $dir/*; do
        echo -e "\t${file#*$dir/}"
    done
}

ngx_reload() {
    read -p "Would you like to reload the Nginx configuration now? (Y/n) " reload
    [[ "$reload" != "n" && "$reload" != "N" ]] && invoke-rc.d nginx reload
}

ngx_error() {
    echo -e "${0##*/}: ERROR: $1"
    [[ "$2" ]] && ngx_help
    exit 1
}

ngx_help() {
    echo "Usage: ${0##*/} [options]"
    echo "Options:"
    echo -e "\t<-e|--enable> <site>\tEnable site"
    echo -e "\t<-d|--disable> <site>\tDisable site"
    echo -e "\t<-l|--list>\t\tList sites"
    echo -e "\t<-h|--help>\t\tDisplay help"
    echo -e "\n\tIf <site> is left out a selection of options will be presented."
    echo -e "\tIt is assumed you are using the default sites-enabled and"
    echo -e "\tsites-disabled located at $NGINX_CONF_DIR."
}

##
# Core Piece
##

case "$1" in
    -e|--enable)    ngx_enable_site;;
    -d|--disable)   ngx_disable_site;;
    -l|--list)  ngx_list_site;;
    -h|--help)  ngx_help;;
    *)      ngx_error "No Options Selected" 1; ngx_help;;
esac

Make it executable with ran chmod 700 /usr/bin/nginx_modsite.

Using nginx_modsite

To list all available virtualhosts, you can run the following command.

$ sudo nginx_modsite -l

Enable virtualhost “example.org”.

$ sudo nginx_modsite -e example.org

Disable virtualhost “example.org”.

$ sudo nginx_modsite -d example.org

About NGINX

Nginx “engine x” is an open source web server that can also be used as a reverse proxy, load balancer, mail proxy and HTTP cache. The software was created by Russian developer Igor Sysoev and publicly released in 2004. Nginx is free and open-source software, released under the terms of the 2-clause BSD license. A large fraction of web servers use Nginx, often as a load balancer.

Nginx is built to offer low memory usage and high concurrency. Rather than creating new processes for each web request, Nginx uses an asynchronous, event-driven approach where requests are handled in a single thread.

With Nginx, one master process can control multiple worker processes. The master maintains the worker processes, while the workers do the actual processing. Because Nginx is asynchronous, each request can be executed by the worker concurrently without blocking other requests.

Nginx vs Apache Usage Stats

Apache is another popular open source web server. In terms of raw numbers, Apache is the most popular web server in existence and is used by 43.6% (down from 47% in 2018) of all websites with a known web server, according to W3Techs. Nginx comes in a close second at 41.8%.

Netcraft ran a survey across 233 million domains and found Apache usage at 31.54% and Nginx usage at 26.20%.

NGINX Reverse Proxy on Debian

NGINX used as a reverse proxy on Debian Linux

The NGINX web server software is developed in C by Igor Sysoev and is released under the BSD license. NGINX is used as a web server, reverse proxy, load balancer and HTTP cache.

Due to its small size and reverse proxy functionality, nginx is also popular for obscuring the true address of botnet commnd and control servers.

Which in turn can also be used in companies and organizations to primarily disguise unsafe Microsoft Windows servers in order to protect against possible weak points.

Install Nginx on Debian Linux

$ apt install nginx certbot python3-certbot-nginx -y

First, we can disable the default virtual host that is pre-configured when Nginx is installed.

$ unlink /etc/nginx/sites-enabled/default

We can edit nginx.conf file in order to configure the NGINX server to act as a reverse proxy here on Debian 12 (bookworm).

we can set worker_processes count based on the number of cores allocating for worker processers. Also, set worker_connections as the number of connections concurrently handled by one processor.

Create the Nginx Reverse Proxy

After disabling the virtual host, we need to create a file called example.domain.com within the /etc/nginx/sites-available directory to keep reverse proxy information.

This is done as follows by creating a file using the vi editor:

$ vi /etc/nginx/sites-available/example.domain.com

Let’s say example.domain.com is a service behind the NGINX proxy with endpoint port 80.

In the file, we need to paste in these content:

server {
    listen 80;
    listen [::]:80;
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name example.domain.com;
    server_tokens off;
    access_log /var/log/nginx/reverse_access.log;
    error_log /var/log/nginx/reverse_error.log;

    location / {
        proxy_pass http://203.0.113.10:80/;
        include proxy_params;
        try_files $uri $uri/ =404;
        proxy_redirect off;
        proxy_ssl_trusted_certificate /etc/nginx/ssl/ca.crt;
    }
}

Once completed, simply save the file and exit the vi editor by hit :wq

In the above command, the considerable point is the proxy_pass is allowing the requests coming through the Nginx reverse proxy to pass along to 203.0.113.10:80, which is the remote server where to pass.

Now, activate the directives by linking to /sites-enabled/ using the following command:

$ ln -s /etc/nginx/sites-available/example.domain.com /etc/nginx/sites-enabled/

Test Nginx Reverse Proxy configuration

Lastly, we need to run an Nginx configuration test and restart Nginx to check its performance. Type the below command to verify the Nginx functioning on the Linux terminal:

$ nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

If the above result is displayed, we can now restart Nginx:

$ systemctl restart nginx

To check whether the Nginx service is listening on port 80, the following command can be executed:

$ netstat -tulpn
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address   Foreign Address     State     PID/Program name
tcp      0    0 0.0.0.0:80          0.0.0.0:*           LISTEN    3706/nginx: master
tcp      0    0 0.0.0.0:22          0.0.0.0:*           LISTEN    681/sshd: /usr/sbin
tcp6     0    0 :::22               :::*                LISTEN    681/sshd: /usr/sbin
tcp6     0    0 :::80               :::*                LISTEN    3706/nginx: master

Content Security Policy (CSP) comes with a whole range of parameters that can be used to fine-tune browser behavior, find here.

Conclusion

NGINX is a powerful web server software used by several hosting companies mainly as reverse proxy or cache and load balancer. It was designed to handle a high volume of requests simultaneously. Therefore, it offers faster loading times and better performance than most other web servers.

Additionally, NGINX uses fewer system resources than other web server software. This feature makes it a cost-effective solution. It is also compatible with a wide range of web applications.

NGINX server provides security to backend servers that exist in the private network by hiding their identity. The backend servers are unknown to the client that are making requests. it also provides a single point of access to multiple backend servers regardless of the backend network topology.