Setting Up and Configuring an Nginx Web Server
Nginx is a high-performance HTTP server and reverse proxy. This guide covers its enstallation, basic configuration, and management on Linux distributions.
Installing Nginx
Installation methods differ by operating system. Below are commands for Ubuntu/Debian and CentOS/RHEL-based systems.
For Ubuntu/Debian:
sudo apt update
sudo apt install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx
For CentOS/RHEL:
sudo yum install epel-release -y
sudo yum install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx
Basic Service Management
After installation, verify the service is running and learn to apply configuraton changes.
Check the current status of the Nginx service:
sudo systemctl status nginx
To apply any configuration file modifications without stopping the service, use the reload command:
sudo systemctl reload nginx
Configuring Server Blocks (Virtual Hosts)
Server blocks allow hosting multiple domains on a single server. Configuration files are typically stored in /etc/nginx/sites-available/ and symlinked to /etc/nginx/sites-enabled/.
- Create a new configuraton file for your domain:
sudo nano /etc/nginx/sites-available/mywebsite.com - Add the following server block configuration. Replace
mywebsite.comand the document root path as needed.server { listen 80; server_name mywebsite.com www.mywebsite.com; root /var/www/mywebsite.com/public_html; index index.html index.htm; location / { try_files $uri $uri/ =404; } } - Create the website directory and a basic HTML file:
sudo mkdir -p /var/www/mywebsite.com/public_html sudo chown -R $USER:$USER /var/www/mywebsite.com/public_html sudo chmod -R 755 /var/www/mywebsite.com echo '<!DOCTYPE html><html><head><title>My Site</title></head><body><h1>Hello World</h1></body></html>' | sudo tee /var/www/mywebsite.com/public_html/index.html - Enable the site by creating a symbolic link and test the configuration:
sudo ln -s /etc/nginx/sites-available/mywebsite.com /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx
Adjusting the Firewall
Allow web traffic through the system firewall.
Using UFW on Ubuntu:
sudo ufw allow 'Nginx Full'
sudo ufw enable
Using firewalld on CentOS:
sudo firewall-cmd --permanent --add-service=http --add-service=https
sudo firewall-cmd --reload
Enabling HTTPS with Let's Encrypt
Secure your site with a free SSL/TLS certificate from Let's Encrypt using the Certbot client.
- Install Certbot and its Nginx plugin.
Ubuntu/Debian:
CentOS/RHEL 7/8:sudo apt install certbot python3-certbot-nginx -ysudo yum install certbot python3-certbot-nginx -y - Obtain and install a certificate for your domain. Certbot will modify your Nginx configuration automatically.
sudo certbot --nginx -d mywebsite.com -d www.mywebsite.com - Certbot sets up automatic renewal. Test the renewal process with a dry run:
sudo certbot renew --dry-run