Home Linux NGINX Best Practices on Initial Setup

NGINX Best Practices on Initial Setup

by Lakindu Jayasena
5.1k views 10 mins read
NginxBestPractices

Nginx is a lightweight, high-performance, and feature-rich open-source web server/proxy server, as well as a load balancer. Most of them have heard of Apache, but Nginx is also up in popularity serving over 50% of the traffic on the internet. The major reason is the fast adoption of Nginx because of its speed and can handle hundreds of thousands of concurrent connections. Since the original release of NGINX however, websites have expanded from basic HTML pages to dynamic, multi-layered content and now support all the components of the modern Web, including WebSocket, HTTP/2, and streaming of multiple video formats and it runs on UNIX, GNU/Linux, BSD variants, Mac OS X, Solaris, and Microsoft Windows.

Though NGINX became recognized as the fastest web server, the scalable underlying architecture has proved ideal for many web tasks beyond serving content. Because it can handle a high number of connections, NGINX is commonly used as a reverse proxy and load balancer to manage incoming traffic and distribute it to upstream servers – anything from database servers to microservices.

This article will help you to install and do the basic configurations on the Nginx server with best practices running on Linux or UNIX-like operating systems.

Installing Nginx Server

Before proceeding with the installation of Nginx, update all the system packages:

apt-get update

Install and start the Nginx service:

apt-get install nginx
systemctl start nginx
systemctl enable nginx    #Automatically start the service on bootup

After the Nginx installation, can check the version of Nginx by using the following command:

nginx -v

First of all, we will see Nginx default configuration files & locations:

  • /etc/nginx/ – The Nginx server configuration directory and nginx.conf is the main configuration file.
  • /etc/nginx/sites-available – Custom all virtual host configuration locations.
  • /etc/nginx/sites-enabled – enabled virtual host configuration location (this is a symbolic link to sites-availabale configurations).
  • /var/www/html – The default document root location.
  • /var/log/nginx – The default log files location.

Configuring the Nginx server blocks (Virtual Host)

This is similar to the virtual host concept in Apache and can be used to encapsulate configuration details and host more than one domain off of a single server.

The default Nginx configuration files are kept inside /etc/nginx/sites-available a directory and it is symbolically linked with files inside /etc/nginx/sites-enabled/ a directory. Usually needs to create a separate file in the sites-available directory for each domain/subdomain (in this post I am using sysopstechnix.com) and set up a symlink in the sites-enabled directory.

Remove the symlink in /etc/nginx/sites-enabled/default to disable the default configuration file.

unlink /etc/nginx/sites-enabled/default

Create a new directory for the document root and create a basic index file inside the /var/www/sysopstechnix.com.

mkdir -p /var/www/sysopstechnix.com/
echo "Welcome to SysOpsTechnix" > /var/www/sysopstechnix.com/index.html

Create a new configuration file /etc/nginx/sites-available/sysopstechnix.com.conf for the website and add the below configurations in the configuration file and save.

server {
    listen  80;
    listen [::]:80;
    server_name sysopstechnix.com www.sysopstechnix.com;
    root /var/www/sysopstechnix.com
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

Configure Nginx to use your SSL/TLS Certificate

Transport Layer Security (TLS) is the successor to Secure Socket Layer (SSL). It provides stronger security and more efficiency and contains enhancements not found in SSL such as Forward Secrecy, compatibility with modern OpenSSL cipher suites, and HSTS.

Create a folder to store the SSL certificates inside the Nginx configuration using the following command.

mkdir /etc/nginx/ssl

Then copy the certificate and the private key file to the created location. Please rename the files to show which domain they are associated with.

cp /path/to/your/certificate.crt /etc/nginx/ssl/sysopstechnix.com.crt
cp /path/to/your/private.key /etc/nginx/ssl/sysopstechnix.com.key

Add the SSL configure details inside the HTTPS server block, define the location of your certificates and Save the file to exit.

server {
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;

    ssl_certificate /etc/nginx/ssl/sysopstechnix.com.crt;
    ssl_certificate_key /etc/nginx/ssl/sysopstechnix.com.key;
    ssl_ciphers         EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH;
    ssl_prefer_server_ciphers on;
    ssl_protocols       TLSv1.2 TLSv1.3;

    server_name sysopstechnix.com www.sysopstechnix.com;

    root /var/www/sysopstechnix.com;
    index index.html;
}

Redirect HTTP Traffic to HTTPS

When end users type your website’s domain, the normal behavior is that the site is loaded over HTTP, which means unencrypted. By configuring HTTP redirection, NGINX will redirect their browser to your site using an HTTPS connection. Also, this is useful to help increase your page rank on search engine results. The only change is to add a redirection inside the HTTP block.

server {
    listen         80;
    server_name    sysopstechnix.com www.sysopstechnix.com;
    return         301 https://sysopstechnix.com$request_uri;
}

Configure Custom Access and Error Log

The Nginx server has an exceptional logging facility that is highly customizable. All client requests to the server are recorded in the access log in a specified format using the ngx_http_log_module module. The default log file is located at /var/log/nginx/access.log on Linux systems and the default format for logging is normally the combined or main format.

You can specify multiple logs using the access_log directives on the same level, here we are using more than one log file in the http or server block.

server{
    #Default log format
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
      
    #request tracing using custom format
    log_format custom '$remote_addr - $remote_user [$time_local] '
                      '"$request" $status $body_bytes_sent '
                      '"$http_referer" "$http_user_agent" '
                      '"$http_x_forwarded_for" $request_id '
                      '$geoip_country_name $geoip_country_code '
                      '$geoip_region_name $geoip_city ';

    #Default log format
    access_log /var/log/nginx/sysopstechnix.com_access.log;

    #Custom log format
    access_log /var/log/nginx/sysopstechnix.com_custom_access.log custom;

    #Error Log
    #Severity Levels: debug, info, notice, warn, error 
    error_log /var/log/nginx/sysopstechnix.com_error.log warn; 

}

Full Configuration Sample

server {
    listen              80;
    listen              [::]:80;
    server_name    sysopstechnix.com www.sysopstechnix.com;
    return         301 https://sysopstechnix.com$request_uri;
}

server {
    listen              443 ssl http2 default_server;
    listen              [::]:443 ssl http2 default_server;
    server_name         sysopstechnix.com www.sysopstechnix.com;
    root                /var/www/sysopstechnix.com;
    index               index.html;

    ssl_certificate /etc/nginx/ssl/sysopstechnix.com.crt;
    ssl_certificate_key /etc/nginx/ssl/sysopstechnix.com.key;
    ssl_ciphers         EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH;
    ssl_prefer_server_ciphers on;
    ssl_protocols       TLSv1.2 TLSv1.3;

    access_log /var/log/nginx/sysopstechnix.com_access.log;
    error_log /var/log/nginx/sysopstechnix.com_error.log warn;

    location / {
         try_files $uri $uri/ =404;
    }
}

Enable & Verify Configuration

Finally, create a new symlink to the /etc/nginx/sites-enabled/ directory for enabling the configuration.

ln -s /etc/nginx/sites-available/sysopstechnix.com /etc/nginx/sites-enabled/

Once the changes have been done in the Nginx configuration files, then should check the configuration for any syntax errors in it using the following command.

nginx -t

Reload your NGINX configuration:

nginx -s reload

Related Articles

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.