#!/bin/bash

# Check if the script is run as root
if [ "$EUID" -ne 0 ]
  then echo "Please run as root"
  exit
fi

# Check which CentOS version is installed
if [[ $(rpm -q --queryformat '%{VERSION}' centos-release) -eq 7 ]]; then
  # Install Nginx on CentOS 7
  yum install -y nginx
  systemctl start nginx
  systemctl enable nginx
elif [[ $(rpm -q --queryformat '%{VERSION}' centos-release) -eq 8 ]]; then
  # Install Nginx on CentOS 8
  dnf install -y nginx
  systemctl start nginx
  systemctl enable nginx
elif [[ $(rpm -q --queryformat '%{VERSION}' centos-release) -eq 9 ]]; then
  # Install Nginx on CentOS 9
  dnf install -y nginx
  systemctl start nginx
  systemctl enable nginx
else
  echo "Unsupported CentOS version"
  exit
fi

# Add firewall rule to allow HTTP traffic
firewall-cmd --add-service=http --permanent
firewall-cmd --reload

echo "Nginx web server installed and started successfully"

Here’s what this script does:

The script first checks if it is run as root, and exits if not.

It then checks which version of CentOS is installed using the rpm -q command.

Depending on the CentOS version, the script installs Nginx web server using yum or dnf package manager, starts the service and enables it to start automatically on boot.

Finally, the script adds a firewall rule to allow HTTP traffic and reloads the firewall.

The script prints a message indicating that Nginx web server has been installed and started successfully.

Note: This script assumes that you have a firewall enabled on your system. If you are using a cloud provider like AWS, make sure to add a rule to your security group to allow incoming HTTP traffic as well.