How to Install Nginx on AlmaLinux 8

NGINX is an open-source, free HTTP server software. In addition to its HTTP server capabilities, NGINX can also function as a proxy server for e-mail (IMAP, POP3, and SMTP) and a reverse proxy and load balancer for HTTP, TCP, and UDP servers. The goal behind NGINX was to create the fastest web server around, and maintaining that excellence is still a central goal of the Nginx project. NGINX consistently beats Apache and other servers in benchmarks measuring web server performance and is now the most popular used web server according to W3Tech.

In the tutorial, you will learn how to install Nginx on AlmaLinux 8 with a free TLS/SSL certificate from Let’s Encrypt.

Prerequisites

  • Recommended OS: AlmaLinux 8.
  • User account: A user account with sudo privilages or root access (su command).

Updating Operating System

Update your AlmaLinux operating system to make sure all existing packages are up to date:

sudo dnf upgrade --refresh

The tutorial will be using the sudo command and assuming you have sudo status.

To verify sudo status on your account:

sudo whoami

Example output showing sudo status:

[joshua@localhost ~]$ sudo whoami
root

To set up an existing or new sudo account, visit our tutorial on How to Add a User to Sudoers on AlmaLinux.

To use the root account, use the following command with the root password to log in.

su

Install Nginx

Method 1. Install Nginx from AlmaLinux AppStream

The first method is to install Nginx from the AlmaLinux App stream. This version is older but stable and secure. If you need to run a primary web server or reverse proxy, installing the App Stream repository is often recommended.

To install Nginx, run the following command.

sudo dnf install nginx

Example output:

How to Install Nginx with Let’s Encrypt TLS/SSL on AlmaLinux 8

Type “Y”, then press the “ENTER KEY” to proceed with the installation.

Next, verify the version build and if the installation was successful.

sudo nginx -v

Example output:

nginx version: nginx/1.14.1

Note, your outputs will be different depending on the module you enable.

Before you continue, you must start the Nginx service.

sudo systemctl start nginx

Next, verify the status to make sure there are no errors.

systemctl status nginx

Example output if all is working correctly:

How to Install Nginx with Let’s Encrypt TLS/SSL on AlmaLinux 8

Method 2. Install Nginx from EPEL

The second option is to install Nginx from the EPEL repository. This will bring you a much more up-to-date version of Nginx that is still considered stable than installing the obsolete latest versions from Nginx itself. The process is relatively easy.

First, install the EPEL repository:

sudo dnf install epel-release

Example output:

How to Install Nginx with Let’s Encrypt TLS/SSL on AlmaLinux 8

Type “Y”, then press the “ENTER KEY” to proceed with the installation.

Now, with the EPEL installed, you need to reset the Nginx modules.

sudo dnf module reset nginx

Next, list the available modules available with dnf from all known repositories.

sudo dnf module list nginx

Example output:

How to Install Nginx with Let’s Encrypt TLS/SSL on AlmaLinux 8

As above, you can either switch to a higher version of stable or mainline. Note the stable version is always in build number, and the mainline is naturally mainline.

To enable one of the new modules from EPEL, use the following in your terminal.

Enable latest stable:

sudo dnf module enable nginx:1.20

Note for stable Nginx EPEL: This may change in the future. Make sure to list the modules and not just copy and paste.

Enable latest mainline:

sudo dnf module enable nginx:mainline

Now, install Nginx:

sudo dnf install nginx

Example output:

How to Install Nginx with Let’s Encrypt TLS/SSL on AlmaLinux 8

Type “Y,” then press the “ENTER KEY” to proceed with the installation.

Next, verify the version build and if the installation was successful.

sudo nginx -v

Example output (Mainline):

nginx version: nginx/1.19.10

Note, your outputs will be different depending on the module you enable.

Before you continue, you must start the Nginx service.

sudo systemctl enable nginx --now

Next, verify the status to make sure there are no errors.

systemctl status nginx

Example output if all is working correctly:

How to Install Nginx with Let’s Encrypt TLS/SSL on AlmaLinux 8

Configure Firewall Rules

It does not automatically add firewall rules to the standard port 80 or 443 ports when installing Nginx. Before you continue, you should set the following rules, this will depend on what ports you will use, but all options are listed.

Open port 80 or HTTP:

sudo firewall-cmd --permanent --zone=public --add-service=http

Open port 443 or HTTPS:

sudo firewall-cmd --permanent --zone=public --add-service=https

Reload firewall to make changes into effect

sudo firewall-cmd --reload

Configure Nginx Server

You will need to have the server’s IP address ready for set up. The easiest way to do this is with the following.

Find Server IP Address

You will need to have the server’s IP address prepared for set up. The easiest way to do this is with the following.

curl -4 icanhazip.com

Example output:

XXX.XXX.XXX.XXX IP address

If the commands are not working, you do not have the curl package installed more than likely. Run the following command:

sudo dnf install curl -y

Once you have your server’s IP address, open up your favorite Internet Browser, and check the default landing page is working.

http://your_server_ip

You should get the following page in your Internet Browser. If you do not get this page but an Nginx error page instead, that is ok as the EPEL release may differ. You are testing to make sure you can reach the Nginx server.

How to Install Nginx with Let’s Encrypt TLS/SSL on AlmaLinux 8

Set Up Site Source Directory

In the tutorial, you will set up a domain called example.com, but you should replace this with your domain name. The tutorial will create the web directories and configure the site files in the parent directory /var/www/.

First, create the directory, for example.com, as follows, using the “-p” flag to make any necessary parent directories:

sudo mkdir -p /var/www/your_domain/html

Second, you will need to assign the owner of the directory.

sudo chown -R $USER:$USER /var/www/your_domain/html

Third, assign the directory’s permissions, so the owner read, write, and execute the files while granting only read and execute permissions to groups and others. You can input the following command:

sudo chmod -R 755 /var/www/your_domain

Alternatively, you can use the /usr/share/nginx/html directory instead, but the /var/www directory method is recommended for new users.

Set up Test HTML page

Fourth, create a test page that you will use to confirm your Nginx server is operational.

nano /var/www/your_domain/html/index.html

Inside the nano editor and new file you have created. Enter the following.

<html>
 <head>
  <title>Welcome to your_domain!</title>
 </head>
 <body>
   <h1>Success!  The your_domain server block is working!</h1>
 </body>
</html>

Save the file (CTRL+O), then exit (CTRL+X).

Create Nginx Server Block

By default, the Nginx server block, similar to Apache virtual hosts, is dealt with in the /etc/nginx/conf.d directory. However, the Nginx installation varies from different versions and distributions utilizing either the conf.d or sites-available/sites-enabled by default. For the tutorial, the site’s directories will be used to keep a standard.

First, make the directories needed for sites-available and sites-enabled. Nginx users would be familiar with this setup as well.

sudo mkdir /etc/nginx/sites-available
sudo mkdir /etc/nginx/sites-enabled

Next, open your nginx.conf file and remove or comment the “include /etc/nginx/default.d/*.conf;” and directly under it add include “/etc/nginx/sites-enabled/*.conf;”.

Example only:

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 4096;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

###EDIT HERE###
#  include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*.conf;
}

As above, a “#” comment was added to include conf.d line, and include sites-enabled was added.

Save the file (CTRL+O) and exit (CTRL+X).

Next, create your server block configuration file. The name your_domain.conf will be used for the tutorial, but this can be named anything you prefer.

sudo nano /etc/nginx/sites-available/your_domain.conf

You can paste the following example code into the block. This is just an HTTP-only example for basic testing.

server {
 listen 80;
 listen [::]:80;

 root /var/www/your_domain/html;

  index index.html index.htm;
  server_name your_domain www.your_domain;

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

The example shows your server is listening for two server names, “your_domain” on port 80.

You will need to change the root directory to the name/location of the root directory you create.

Enabled Nginx Server Block

You must link the configuration files from sites-available to sites-enabled in your Nginx directory to enable Nginx server blocks. This can be done with the ln -s command as follows.

sudo ln -s /etc/nginx/sites-available/your_domain.conf /etc/nginx/sites-enabled/

Final Configuration & Test run

In the final stage, you will need to open your default nginx.conf file.

sudo nano /etc/nginx/nginx.conf

And uncomment the following line.

server_names_hash_bucket_size 64;

The server name’s hash bucket size is changed as sometimes problems arise from adding additional servers.

Next, test your Nginx to make sure it’s working before properly restarting.

sudo nginx -t

The output should be if no errors in the syntax:

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

If you have the following ok output, restart the Nginx server for the changes to take place.

sudo systemctl restart nginx

Now open your Internet Browser and type in the server domain name. You should see your server block is live.

Secure Nginx with Let’s Encrypt SSL Free Certificate

Ideally, you would want to run your Nginx on HTTPS using an SSL certificate. The best way to do this is to use Let’s Encrypt, a free, automated, and open certificate authority run by the nonprofit Internet Security Research Group (ISRG).

First, install the EPEL repository and the mod_ssl package for better-updated packages and security.

sudo dnf install epel-release mod_ssl -y

Next, install the certbot package as follows:

sudo dnf install python3-certbot-nginx -y

Once installed, run the following command to start the creation of your certificate:

sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email you@example.com -d www.example.com

This is the ideal setup that includes force HTTPS 301 redirects, Strict-Transport-Security header, and OCSP Stapling. Just make sure to adjust the e-mail and domain name to your requirements.

Now your URL will be HTTPS://www.example.com instead of HTTP://www.example.com.

Note, if you use the old HTTP URL, it will automatically redirect to HTTPS.

Optionally, you can set a cron job to renew the certificates automatically. Certbot offers a script that does this automatically, and you can first test to make sure everything is working by performing a dry run.

sudo certbot renew --dry-run

If everything is working, open your crontab window by using the following terminal command.

sudo crontab -e

Next, specify the time when it should auto-renew. This should be checked daily at a minimum, and if the certificate needs to be renewed, the script will not update the certificate. If you need help with finding a good time to set, use the crontab.guru free tool.

00 00 */1 * * /usr/sbin/certbot-auto renew

Save (CTRL+O) then exit (CTRL+X), and the cronjob will be automatically enabled.

Managing Nginx Service

Now that you have Nginx running on your server successfully, some management keynotes are as follows.

To stop Nginx webserver:

sudo systemctl stop nginx

To start Nginx webserver:

sudo systemctl start nginx

To restart the Nginx webserver:

sudo systemctl restart nginx

To reload the Nginx webserver (For more minor changes not requiring a restart):

sudo systemctl reload nginx

To disable Nginx on server boot:

sudo systemctl disable nginx

To start Nginx on server boot (Automatically enabled on installation):

sudo systemctl enable nginx

How to Access Nginx Server Logs

Nginx Logs Directory

By default, all NGINX access/error logs, unless you have changed them, are located in the log directory, which the following command can view.

First, navigate to the logs directory and list files:

cd /var/log/nginx && ls -l

You should find the following access and error files:

Access Log:

/var/log/nginx/access.log

Error Log:

/var/log/nginx/error.log

To view logs in real-time in your terminal using the sudo tail -f /location/of/log path command.

Example:

sudo tail -f /var/log/nginx/access.log

Another option is to print the last X amount of lines. For example, X is replaced with 30 to print 30 lines by adding the -n 30 flag.

sudo tail -f /var/log/nginx/access.log -n 30

These are just some examples of reading logs, and grep can be helpful as well.

How to Configure Nginx Log Rotate

Nginx automatically installs log rotation and configure it to default which is to rotate daily. You can change these settings by accessing the file as shown below.

sudo nano /etc/nginx/logrotate.d/nginx

Next, you will see the same if not similar file structure. You can modify the contents here. Mostly you can change how many logs to keep or go from daily to weekly. This should be left on default unless you have specific log requirement needs for software like fail2ban monitoring or similar.

/var/log/nginx/*.log {
  daily
  missingok
  rotate 14
  compress
  delaycompress
  notifempty
  create 0640 www-data adm
  sharedscripts
  prerotate
  if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
  run-parts /etc/logrotate.d/httpd-prerotate; \
  fi \
  endscript
  postrotate
  invoke-rc.d nginx rotate >/dev/null 2>&1
  endscript
}

The main settings you will probably want to change is the following:

  • Daily – This can be changed to Weekly, Monthly. This shouild be kept at daily, or else going through the log file will be difficult.
  • Rotate 14 – This is how many logs to keep and remove, so at max there is only 14 logs, if you only want to keep 7 days worth of logs change this to 7.

Its recommended not to touch any other settings unless you know what you are doing.

How to Update Nginx

Nginx will be updated by default when a new version hits the repositories. Before upgrading, it’s always advised to back up your Nginx directory or, at the very least, the nginx.conf file. You can do either with the following command.

Back up nginx.conf (Highly Recommended):

sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx-backup.conf

Back up your entire Nginx folder if you prefer:

sudo cp /etc/nginx/ /etc/nginx-bkup

Next, run the standard update command.

sudo dnf upgrade --refresh

If an upgrade is available, run the upgrade.

You may be prompted this during an upgrade or installation, but manually doing this beforehand is pretty essential. For large Nginx configurations of multiple sites, backing up to something like Github or Gitlab would be even more beneficial.

How to Remove (Uninstall) Nginx

To remove Nginx if you no longer use it, this can be done using the following command:

sudo dnf autoremove nginx

This command will also remove any unused dependencies that came with the installation.

Remember, if you install Nginx using EPEL and would like to reset it to re-install the original version, use the following command as stated earlier.

sudo dnf modules reset nginx

Comments and Conclusion

In the tutorial, you have learned to install and set up basic Nginx configuration on your domain on AlmaLinux 8 and create a free SSL certificate using Let’s Encrypt. Overall, Nginx is the most used and popular web application software now, with every month and year surpassing taking more market share from Apache.

Some new contenders are starting to pop up, such as Openlitespeed but given these other web applications, for now, focus on specific things like WordPress. Nginx will be the go-to web application for some time.



Follow LinuxCapable.com!

Like to get automatic updates? Follow us on one of our social media accounts!