This Document is actively being developed as a part of ongoing AlmaLinux learning efforts. Chapters will be added periodically.
This is the multi-page printable view of this section. Click here to print.
Nginx Web Server on AlmaLinux 9
- 1: How to Install Nginx on AlmaLinux
- 2: How to Configure Virtual Hosting with Nginx on AlmaLinux
- 3: How to Configure SSL/TLS with Nginx on AlmaLinux
- 4: How to Enable Userdir with Nginx on AlmaLinux
- 5: How to Set Up Basic Authentication with Nginx on AlmaLinux
- 6: How to Use CGI Scripts with Nginx on AlmaLinux
- 7: How to Use PHP Scripts with Nginx on AlmaLinux
- 8: How to Set Up Nginx as a Reverse Proxy on AlmaLinux
- 9: How to Set Up Nginx Load Balancing on AlmaLinux
- 10: How to Use the Stream Module with Nginx on AlmaLinux
1 - How to Install Nginx on AlmaLinux
Nginx (pronounced “Engine-X”) is a powerful, lightweight, and highly customizable web server that also functions as a reverse proxy, load balancer, and HTTP cache. Its performance, scalability, and ease of configuration make it a popular choice for hosting websites and managing web traffic.
For users of AlmaLinux, a robust and RHEL-compatible operating system, Nginx offers a seamless way to deploy and manage web applications. This guide will walk you through the step-by-step process of installing and configuring Nginx on AlmaLinux.
Prerequisites
Before we begin, ensure you meet these prerequisites:
- A Running AlmaLinux Instance: The tutorial assumes AlmaLinux 8 or later is installed.
- Sudo or Root Access: You’ll need administrative privileges for installation and configuration.
- A Basic Understanding of the Command Line: Familiarity with Linux commands will be helpful.
Step 1: Update Your AlmaLinux System
Keeping your system updated ensures that all installed packages are current and secure. Open a terminal and run the following commands:
sudo dnf update -y
sudo reboot
Rebooting ensures all updates are applied correctly.
Step 2: Install Nginx
Add the EPEL Repository
Nginx is available in AlmaLinux’s Extra Packages for Enterprise Linux (EPEL) repository. First, ensure the EPEL repository is installed:
sudo dnf install epel-release -y
Install Nginx
Once the EPEL repository is enabled, install Nginx using the dnf
package manager:
sudo dnf install nginx -y
Verify Installation
Check the installed Nginx version to ensure it was installed correctly:
nginx -v
You should see the version of Nginx that was installed.
Step 3: Start and Enable Nginx
After installation, start the Nginx service:
sudo systemctl start nginx
Enable Nginx to start automatically on boot:
sudo systemctl enable nginx
Verify that Nginx is running:
sudo systemctl status nginx
You should see an output indicating that Nginx is active and running.
Step 4: Adjust the Firewall to Allow HTTP and HTTPS Traffic
By default, AlmaLinux’s firewall blocks web traffic. To allow HTTP and HTTPS traffic, update the firewall settings:
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
Confirm that the changes were applied:
sudo firewall-cmd --list-all
You should see HTTP and HTTPS listed under “services”.
Step 5: Verify Nginx Installation
Open a web browser and navigate to your server’s IP address:
http://your-server-ip
You should see the default Nginx welcome page, confirming that the installation was successful.
Step 6: Configure Nginx
Understanding Nginx Directory Structure
The main configuration files for Nginx are located in the following directories:
- /etc/nginx/nginx.conf: The primary Nginx configuration file.
- /etc/nginx/conf.d/: A directory for additional configuration files.
- /usr/share/nginx/html/: The default web document root directory.
Create a New Server Block
A server block in Nginx is equivalent to a virtual host in Apache. It allows you to host multiple websites on the same server.
Create a new configuration file for your website:
sudo nano /etc/nginx/conf.d/yourdomain.conf
Add the following configuration:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com;
root /var/www/yourdomain;
index index.html;
location / {
try_files $uri $uri/ =404;
}
error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
}
}
Replace yourdomain.com
with your actual domain name or IP address. Save and close the file.
Create the Document Root
Create the document root directory for your website:
sudo mkdir -p /var/www/yourdomain
Add a sample index.html
file:
echo "<h1>Welcome to YourDomain.com</h1>" | sudo tee /var/www/yourdomain/index.html
Set proper ownership and permissions:
sudo chown -R nginx:nginx /var/www/yourdomain
sudo chmod -R 755 /var/www/yourdomain
Step 7: Test Nginx Configuration
Before restarting Nginx, test the configuration for syntax errors:
sudo nginx -t
If the output indicates “syntax is ok” and “test is successful,” restart Nginx:
sudo systemctl restart nginx
Step 8: Secure Nginx with SSL/TLS
To secure your website with HTTPS, install SSL/TLS certificates. You can use Let’s Encrypt for free SSL certificates.
Install Certbot
Install Certbot and its Nginx plugin:
sudo dnf install certbot python3-certbot-nginx -y
Obtain and Configure SSL Certificate
Run the following command to obtain and install an SSL certificate for your domain:
sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
Follow the prompts to complete the process. Certbot will automatically configure Nginx to use the certificate.
Verify HTTPS Setup
Once completed, test your HTTPS configuration by navigating to:
https://yourdomain.com
You should see a secure connection with a padlock in the browser’s address bar.
Set Up Automatic Renewal
Ensure your SSL certificate renews automatically:
sudo systemctl enable certbot-renew.timer
Test the renewal process:
sudo certbot renew --dry-run
Step 9: Monitor and Maintain Nginx
Log Files
Monitor Nginx logs for troubleshooting and performance insights:
- Access Logs:
/var/log/nginx/access.log
- Error Logs:
/var/log/nginx/error.log
Use the tail
command to monitor logs in real-time:
sudo tail -f /var/log/nginx/access.log /var/log/nginx/error.log
Restart and Reload Nginx
Reload Nginx after making configuration changes:
sudo systemctl reload nginx
Restart Nginx if it’s not running properly:
sudo systemctl restart nginx
Update Nginx
Keep Nginx updated to ensure you have the latest features and security patches:
sudo dnf update nginx
Conclusion
By following this guide, you’ve successfully installed and configured Nginx on AlmaLinux. From serving static files to securing your server with SSL/TLS, Nginx is now ready to host your websites or applications efficiently.
For further optimization, consider exploring advanced Nginx features such as reverse proxying, load balancing, caching, and integrating dynamic content through FastCGI or uWSGI. By leveraging Nginx’s full potential, you can ensure high-performance and secure web hosting tailored to your needs.
2 - How to Configure Virtual Hosting with Nginx on AlmaLinux
In today’s web-hosting landscape, virtual hosting allows multiple websites to run on a single server, saving costs and optimizing server resources. Nginx, a popular open-source web server, excels in performance, scalability, and flexibility, making it a go-to choice for hosting multiple domains or websites on a single server. Paired with AlmaLinux, a CentOS alternative known for its stability and compatibility, this combination provides a powerful solution for virtual hosting.
This guide walks you through configuring virtual hosting with Nginx on AlmaLinux. By the end, you’ll be equipped to host multiple websites on your AlmaLinux server with ease.
What is Virtual Hosting?
Virtual hosting is a server configuration method that enables a single server to host multiple domains or websites. With Nginx, there are two types of virtual hosting configurations:
- Name-based Virtual Hosting: Multiple domains share the same IP address, and Nginx determines which website to serve based on the domain name in the HTTP request.
- IP-based Virtual Hosting: Each domain has a unique IP address, which requires additional IP addresses.
For most use cases, name-based virtual hosting is sufficient and cost-effective. This tutorial focuses on that method.
Prerequisites
Before proceeding, ensure the following:
- A server running AlmaLinux with a sudo-enabled user.
- Nginx installed. If not installed, refer to the Nginx documentation or the instructions below.
- Domain names pointed to your server’s IP address.
- Basic understanding of Linux command-line operations.
Step-by-Step Guide to Configure Virtual Hosting with Nginx on AlmaLinux
Step 1: Update Your System
Begin by updating your system packages to ensure compatibility and security.
sudo dnf update -y
Step 2: Install Nginx
If Nginx is not already installed on your system, install it using the following commands:
sudo dnf install nginx -y
Once installed, enable and start Nginx:
sudo systemctl enable nginx
sudo systemctl start nginx
You can verify the installation by visiting your server’s IP address in a browser. If Nginx is installed correctly, you’ll see the default welcome page.
Step 3: Configure DNS Records
Ensure your domain names are pointed to the server’s IP address. Log in to your domain registrar’s dashboard and configure A records to link the domains to your server.
Example:
- Domain:
example1.com
→ A record →192.168.1.100
- Domain:
example2.com
→ A record →192.168.1.100
Allow some time for the DNS changes to propagate.
Step 4: Create Directory Structures for Each Website
Organize your websites by creating a dedicated directory for each domain. This will help manage files efficiently.
sudo mkdir -p /var/www/example1.com/html
sudo mkdir -p /var/www/example2.com/html
Set appropriate ownership and permissions for these directories:
sudo chown -R $USER:$USER /var/www/example1.com/html
sudo chown -R $USER:$USER /var/www/example2.com/html
sudo chmod -R 755 /var/www
Next, create sample HTML files for testing:
echo "<h1>Welcome to Example1.com</h1>" > /var/www/example1.com/html/index.html
echo "<h1>Welcome to Example2.com</h1>" > /var/www/example2.com/html/index.html
Step 5: Configure Virtual Host Files
Nginx stores its server block (virtual host) configurations in /etc/nginx/conf.d/
by default. Create separate configuration files for each domain.
sudo nano /etc/nginx/conf.d/example1.com.conf
Add the following content:
server {
listen 80;
server_name example1.com www.example1.com;
root /var/www/example1.com/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
access_log /var/log/nginx/example1.com.access.log;
error_log /var/log/nginx/example1.com.error.log;
}
Save and exit the file, then create another configuration for the second domain:
sudo nano /etc/nginx/conf.d/example2.com.conf
Add similar content, replacing domain names and paths:
server {
listen 80;
server_name example2.com www.example2.com;
root /var/www/example2.com/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
access_log /var/log/nginx/example2.com.access.log;
error_log /var/log/nginx/example2.com.error.log;
}
Step 6: Test and Reload Nginx Configuration
Verify your Nginx configuration for syntax errors:
sudo nginx -t
If the test is successful, reload Nginx to apply the changes:
sudo systemctl reload nginx
Step 7: Verify Virtual Hosting Setup
Open a browser and visit your domain names (example1.com
and example2.com
). You should see the corresponding welcome messages. This confirms that Nginx is serving different content based on the domain name.
Optional: Enable HTTPS with Let’s Encrypt
Securing your websites with HTTPS is essential for modern web hosting. Use Certbot, a tool from Let’s Encrypt, to obtain and install SSL/TLS certificates.
Install Certbot and the Nginx plugin:
sudo dnf install certbot python3-certbot-nginx -y
Obtain SSL certificates:
sudo certbot --nginx -d example1.com -d www.example1.com sudo certbot --nginx -d example2.com -d www.example2.com
Certbot will automatically configure Nginx to redirect HTTP traffic to HTTPS. Test the new configuration:
sudo nginx -t sudo systemctl reload nginx
Verify HTTPS by visiting your domains (
https://example1.com
andhttps://example2.com
).
Troubleshooting Tips
- 404 Errors: Ensure the
root
directory path in your configuration files matches the actual directory containing your website files. - Nginx Not Starting: Check for syntax errors using
nginx -t
and inspect logs at/var/log/nginx/error.log
. - DNS Issues: Confirm that your domain’s A records are correctly pointing to the server’s IP address.
Conclusion
Configuring virtual hosting with Nginx on AlmaLinux is a straightforward process that enables you to efficiently host multiple websites on a single server. By organizing your files, creating server blocks, and optionally securing your sites with HTTPS, you can deliver robust and secure hosting solutions. AlmaLinux and Nginx provide a reliable foundation for web hosting, whether for personal projects or enterprise-level applications.
With this setup, you’re ready to scale your hosting capabilities and offer seamless web services.
3 - How to Configure SSL/TLS with Nginx on AlmaLinux
In today’s digital landscape, securing your website with SSL/TLS is not optional—it’s essential. SSL/TLS encryption not only protects sensitive user data but also enhances search engine rankings and builds user trust. If you’re running a server with AlmaLinux and Nginx, setting up SSL/TLS certificates is straightforward and crucial for securing your web traffic.
This comprehensive guide will walk you through the steps to configure SSL/TLS with Nginx on AlmaLinux, including obtaining free SSL/TLS certificates from Let’s Encrypt using Certbot.
What is SSL/TLS?
SSL (Secure Sockets Layer) and its successor, TLS (Transport Layer Security), are cryptographic protocols that secure communications over a network. They encrypt data exchanged between a client (browser) and server, ensuring privacy and integrity.
Websites secured with SSL/TLS display a padlock icon in the browser’s address bar and use the https://
prefix instead of http://
.
Prerequisites
Before starting, ensure the following:
- AlmaLinux server with sudo privileges.
- Nginx installed and running. If not installed, follow the Nginx installation section below.
- Domain name(s) pointed to your server’s IP address (A records configured in your domain registrar’s DNS settings).
- Basic familiarity with the Linux command line.
Step-by-Step Guide to Configure SSL/TLS with Nginx on AlmaLinux
Step 1: Update System Packages
Start by updating the system packages to ensure compatibility and security.
sudo dnf update -y
Step 2: Install Nginx (if not already installed)
If Nginx is not installed, you can do so using:
sudo dnf install nginx -y
Enable and start the Nginx service:
sudo systemctl enable nginx
sudo systemctl start nginx
To verify the installation, visit your server’s IP address in a browser. The default Nginx welcome page should appear.
Step 3: Install Certbot for Let’s Encrypt
Certbot is a tool that automates the process of obtaining and installing SSL/TLS certificates from Let’s Encrypt.
Install Certbot and its Nginx plugin:
sudo dnf install certbot python3-certbot-nginx -y
Step 4: Configure Nginx Server Blocks (Optional)
If you’re hosting multiple domains, create a server block for each domain in Nginx. For example, to create a server block for example.com
:
Create the directory for your website files:
sudo mkdir -p /var/www/example.com/html
Set the appropriate permissions:
sudo chown -R $USER:$USER /var/www/example.com/html sudo chmod -R 755 /var/www
Add a sample HTML file:
echo "<h1>Welcome to Example.com</h1>" > /var/www/example.com/html/index.html
Create an Nginx server block file:
sudo nano /etc/nginx/conf.d/example.com.conf
Add the following configuration:
server { listen 80; server_name example.com www.example.com; root /var/www/example.com/html; index index.html; location / { try_files $uri $uri/ =404; } access_log /var/log/nginx/example.com.access.log; error_log /var/log/nginx/example.com.error.log; }
Test and reload Nginx:
sudo nginx -t sudo systemctl reload nginx
Step 5: Obtain an SSL/TLS Certificate with Certbot
To secure your domain, run Certbot’s Nginx plugin:
sudo certbot --nginx -d example.com -d www.example.com
During this process, Certbot will:
- Verify your domain ownership.
- Automatically configure Nginx to use SSL/TLS.
- Set up automatic redirection from HTTP to HTTPS.
Step 6: Test SSL/TLS Configuration
After the certificate installation, test the SSL/TLS configuration:
- Visit your website using
https://
(e.g.,https://example.com
) to verify the SSL/TLS certificate is active. - Use an online tool like SSL Labs’ SSL Test to ensure proper configuration.
Understanding Nginx SSL/TLS Configuration
Certbot modifies your Nginx configuration to enable SSL/TLS. Let’s break down the key elements:
SSL Certificate and Key Paths:
Certbot creates certificates in
/etc/letsencrypt/live/<your-domain>/
.ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
SSL Protocols and Ciphers:
Modern Nginx configurations disable outdated protocols like SSLv3 and use secure ciphers:
ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5;
HTTP to HTTPS Redirection:
Certbot sets up a redirection block to ensure all traffic is secured:
server { listen 80; server_name example.com www.example.com; return 301 https://$host$request_uri; }
Step 7: Automate SSL/TLS Certificate Renewal
Let’s Encrypt certificates expire every 90 days. Certbot includes a renewal script to automate this process. Test the renewal process:
sudo certbot renew --dry-run
If successful, Certbot will renew certificates automatically via a cron job.
Step 8: Optimize SSL/TLS Performance (Optional)
To enhance security and performance, consider these additional optimizations:
Enable HTTP/2:
HTTP/2 improves loading times by allowing multiple requests over a single connection. Add the
http2
directive in thelisten
line:listen 443 ssl http2;
Use Stronger Ciphers:
Configure Nginx with a strong cipher suite. Example:
ssl_ciphers EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH; ssl_prefer_server_ciphers on;
Enable OCSP Stapling:
OCSP Stapling improves SSL handshake performance by caching certificate status:
ssl_stapling on; ssl_stapling_verify on; resolver 8.8.8.8 8.8.4.4;
Add HSTS Header:
Enforce HTTPS by adding the HTTP Strict Transport Security (HSTS) header:
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
Troubleshooting SSL/TLS Issues
Nginx Fails to Start:
Check for syntax errors:
sudo nginx -t
Review logs in
/var/log/nginx/error.log
.Certificate Expired:
If certificates are not renewed automatically, manually renew them:
sudo certbot renew
Mixed Content Warnings:
Ensure all resources (images, scripts, styles) are loaded over HTTPS.
Conclusion
Configuring SSL/TLS with Nginx on AlmaLinux is a critical step for securing your websites and building user trust. By using Certbot with Let’s Encrypt, you can easily obtain and manage free SSL/TLS certificates. The process includes creating server blocks, obtaining certificates, configuring HTTPS, and optimizing SSL/TLS settings for enhanced security and performance.
With the steps in this guide, you’re now equipped to secure your websites with robust encryption, ensuring privacy and security for your users.
4 - How to Enable Userdir with Nginx on AlmaLinux
The userdir
module is a useful feature that allows individual users on a Linux server to host their own web content in directories under their home folders. By enabling userdir
with Nginx on AlmaLinux, you can set up a system where users can create personal websites or test environments without needing root or administrative access to the web server configuration.
This guide explains how to enable and configure userdir
with Nginx on AlmaLinux, step by step.
What Is userdir
?
The userdir
feature is a mechanism in Unix-like operating systems that allows each user to have a web directory within their home directory. By default, the directory is typically named public_html
, and it can be accessed via a URL such as:
http://example.com/~username/
This feature is particularly useful in shared hosting environments, educational setups, or scenarios where multiple users need isolated web development environments.
Prerequisites
Before enabling userdir
, ensure the following:
- AlmaLinux installed and running with root or sudo access.
- Nginx installed and configured as the web server.
- At least one non-root user account available for testing.
- Basic familiarity with Linux commands and file permissions.
Step-by-Step Guide to Enable Userdir with Nginx
Step 1: Update Your System
Start by updating your AlmaLinux system to ensure it has the latest packages and security updates:
sudo dnf update -y
Step 2: Install Nginx (if not already installed)
If Nginx isn’t installed, you can install it with the following command:
sudo dnf install nginx -y
After installation, enable and start Nginx:
sudo systemctl enable nginx
sudo systemctl start nginx
Verify the installation by visiting your server’s IP address in a browser. The default Nginx welcome page should appear.
Step 3: Create User Accounts
If you don’t already have user accounts on your system, create one for testing purposes. Replace username
with the desired username:
sudo adduser username
sudo passwd username
This creates a new user and sets a password for the account.
Step 4: Create the public_html
Directory
For each user who needs web hosting, create a public_html
directory inside their home directory:
mkdir -p /home/username/public_html
Set appropriate permissions so Nginx can serve files from this directory:
chmod 755 /home/username
chmod 755 /home/username/public_html
The 755
permissions ensure that the directory is readable by others, while still being writable only by the user.
Step 5: Add Sample Content
To test the userdir
setup, add a sample HTML file inside the user’s public_html
directory:
echo "<h1>Welcome to Userdir for username</h1>" > /home/username/public_html/index.html
Step 6: Configure Nginx for Userdir
Nginx doesn’t natively support userdir
out of the box, so you’ll need to manually configure it by adding a custom server block.
Open the Nginx configuration file:
sudo nano /etc/nginx/conf.d/userdir.conf
Add the following configuration to enable
userdir
:server { listen 80; server_name example.com; location ~ ^/~([a-zA-Z0-9_-]+)/ { alias /home/$1/public_html/; autoindex on; index index.html index.htm; try_files $uri $uri/ =404; } error_log /var/log/nginx/userdir_error.log; access_log /var/log/nginx/userdir_access.log; }
- The
location
block uses a regular expression to capture the~username
pattern from the URL. - The
alias
directive maps the request to the corresponding user’spublic_html
directory. - The
try_files
directive ensures that the requested file exists or returns a404
error.
- The
Save and exit the file.
Step 7: Test and Reload Nginx Configuration
Before reloading Nginx, test the configuration for syntax errors:
sudo nginx -t
If the test is successful, reload Nginx to apply the changes:
sudo systemctl reload nginx
Step 8: Test the Userdir Setup
Open a browser and navigate to:
http://example.com/~username/
You should see the sample HTML content you added earlier: Welcome to Userdir for username
.
If you don’t see the expected output, check Nginx logs for errors:
sudo tail -f /var/log/nginx/userdir_error.log
Managing Permissions and Security
File Permissions
For security, ensure that users cannot access each other’s files. Use the following commands to enforce stricter permissions:
chmod 711 /home/username
chmod 755 /home/username/public_html
chmod 644 /home/username/public_html/*
- 711 for the user’s home directory ensures others can access the
public_html
directory without listing the contents of the home directory. - 755 for the
public_html
directory allows files to be served by Nginx. - 644 for files ensures they are readable by others but writable only by the user.
Isolating User Environments
To further isolate user environments, consider enabling SELinux or setting up chroot jails. This ensures that users cannot browse or interfere with system files or other users’ data.
Troubleshooting
1. 404 Errors for User Directories
- Verify that the
public_html
directory exists for the user. - Check the permissions of the user’s home directory and
public_html
folder.
2. Nginx Configuration Errors
- Use
nginx -t
to identify syntax errors. - Check the
/var/log/nginx/error.log
file for additional details.
3. Permissions Denied
Ensure that the
public_html
directory and its files have the correct permissions.Confirm that SELinux is not blocking access. If SELinux is enabled, you may need to adjust its policies:
sudo setsebool -P httpd_enable_homedirs 1 sudo chcon -R -t httpd_sys_content_t /home/username/public_html
Additional Considerations
Enabling HTTPS for Userdir
For added security, configure HTTPS using an SSL certificate. Tools like Let’s Encrypt Certbot can help you obtain free certificates. Add SSL support to your userdir
configuration:
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
location ~ ^/~([a-zA-Z0-9_-]+)/ {
alias /home/$1/public_html/;
autoindex on;
index index.html index.htm;
try_files $uri $uri/ =404;
}
}
Disabling Directory Listings
If you don’t want directory listings to be visible, remove the autoindex on;
line from the Nginx configuration.
Conclusion
By enabling userdir
with Nginx on AlmaLinux, you provide individual users with a secure and efficient way to host their own web content. This is especially useful in shared hosting or development environments where users need isolated yet easily accessible web spaces.
With proper configuration, permissions, and optional enhancements like HTTPS, the userdir
feature becomes a robust tool for empowering users while maintaining security and performance.
5 - How to Set Up Basic Authentication with Nginx on AlmaLinux
Securing your web resources is a critical part of managing a web server. One simple yet effective way to restrict access to certain sections of your website or web applications is by enabling Basic Authentication in Nginx. This method prompts users for a username and password before allowing access, providing an extra layer of security for sensitive or private content.
In this guide, we will walk you through the steps to configure Basic Authentication on Nginx running on AlmaLinux, covering everything from prerequisites to fine-tuning the configuration for security and performance.
What is Basic Authentication?
Basic Authentication is an HTTP-based method for securing web content. When a user attempts to access a restricted area, the server sends a challenge requesting a username and password. The browser then encodes these credentials in Base64 and transmits them back to the server for validation. If the credentials are correct, access is granted; otherwise, access is denied.
While Basic Authentication is straightforward to implement, it is often used in combination with HTTPS to encrypt the credentials during transmission and prevent interception.
Prerequisites
Before we begin, ensure the following:
- AlmaLinux server with root or sudo privileges.
- Nginx installed and configured. If not, refer to the installation steps below.
- A basic understanding of the Linux command line.
- Optional: A domain name pointed to your server’s IP address for testing.
Step-by-Step Guide to Configuring Basic Authentication
Step 1: Update Your AlmaLinux System
To ensure your server is running the latest packages, update the system with:
sudo dnf update -y
Step 2: Install Nginx (If Not Already Installed)
If Nginx is not installed, install it using:
sudo dnf install nginx -y
Enable and start Nginx:
sudo systemctl enable nginx
sudo systemctl start nginx
Verify that Nginx is running by visiting your server’s IP address in a web browser. You should see the default Nginx welcome page.
Step 3: Install htpasswd
Utility
The htpasswd
command-line utility from the httpd-tools package is used to create and manage username/password pairs for Basic Authentication. Install it with:
sudo dnf install httpd-tools -y
Step 4: Create a Password File
The htpasswd
utility generates a file to store the usernames and encrypted passwords. For security, place this file in a directory that is not publicly accessible. For example, create a directory named /etc/nginx/auth/
:
sudo mkdir -p /etc/nginx/auth
Now, create a password file and add a user. Replace username
with your desired username:
sudo htpasswd -c /etc/nginx/auth/.htpasswd username
You will be prompted to set and confirm a password. The -c
flag creates the file. To add additional users later, omit the -c
flag:
sudo htpasswd /etc/nginx/auth/.htpasswd anotheruser
Step 5: Configure Nginx to Use Basic Authentication
Next, modify your Nginx configuration to enable Basic Authentication for the desired location or directory. For example, let’s restrict access to a subdirectory /admin
.
Edit the Nginx server block configuration file:
Open the Nginx configuration file for your site. For the default site, edit
/etc/nginx/conf.d/default.conf
:sudo nano /etc/nginx/conf.d/default.conf
Add Basic Authentication to the desired location:
Within the
server
block, add the following:location /admin { auth_basic "Restricted Area"; # Message shown in the authentication prompt auth_basic_user_file /etc/nginx/auth/.htpasswd; }
This configuration tells Nginx to:
- Display the authentication prompt with the message “Restricted Area”.
- Use the password file located at
/etc/nginx/auth/.htpasswd
.
Save and exit the file.
Step 6: Test and Reload Nginx Configuration
Before reloading Nginx, test the configuration for syntax errors:
sudo nginx -t
If the test is successful, reload Nginx to apply the changes:
sudo systemctl reload nginx
Step 7: Test Basic Authentication
Open a browser and navigate to the restricted area, such as:
http://your-domain.com/admin
You should be prompted to enter a username and password. Use the credentials created with the htpasswd
command. If the credentials are correct, you’ll gain access; otherwise, access will be denied.
Securing Basic Authentication with HTTPS
Basic Authentication transmits credentials in Base64 format, which can be easily intercepted if the connection is not encrypted. To protect your credentials, you must enable HTTPS.
Step 1: Install Certbot for Let’s Encrypt
Install Certbot and its Nginx plugin:
sudo dnf install certbot python3-certbot-nginx -y
Step 2: Obtain an SSL Certificate
Run Certbot to obtain and automatically configure SSL/TLS for your domain:
sudo certbot --nginx -d your-domain.com -d www.your-domain.com
Certbot will prompt you for an email address and ask you to agree to the terms of service. It will then configure HTTPS for your site.
Step 3: Verify HTTPS
After the process completes, visit your site using https://
:
https://your-domain.com/admin
The connection should now be encrypted, securing your Basic Authentication credentials.
Advanced Configuration Options
1. Restrict Basic Authentication to Specific Methods
You can limit Basic Authentication to specific HTTP methods, such as GET
and POST
, by modifying the location
block:
location /admin {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/auth/.htpasswd;
limit_except GET POST {
deny all;
}
}
2. Protect Multiple Locations
To apply Basic Authentication to multiple locations, you can define it in a higher-level block, such as the server
or http
block. For example:
server {
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/auth/.htpasswd;
location /admin {
# Specific settings for /admin
}
location /secure {
# Specific settings for /secure
}
}
3. Customize Authentication Messages
The auth_basic
directive message can be customized to provide context for the login prompt. For example:
auth_basic "Enter your credentials to access the admin panel";
Troubleshooting Common Issues
1. Nginx Fails to Start or Reload
- Check for syntax errors with
nginx -t
. - Review the Nginx error log for details:
/var/log/nginx/error.log
.
2. Password Prompt Not Appearing
Ensure the
auth_basic_user_file
path is correct and accessible by Nginx.Verify file permissions for
/etc/nginx/auth/.htpasswd
.sudo chmod 640 /etc/nginx/auth/.htpasswd sudo chown root:nginx /etc/nginx/auth/.htpasswd
3. Credentials Not Accepted
- Double-check the username and password in the
.htpasswd
file. - Regenerate the password file if needed.
Conclusion
Basic Authentication is a simple yet effective method to secure sensitive areas of your website. When configured with Nginx on AlmaLinux, it provides a quick way to restrict access without the need for complex user management systems. However, always combine Basic Authentication with HTTPS to encrypt credentials and enhance security.
By following this guide, you now have a secure and functional Basic Authentication setup on your AlmaLinux server. Whether for admin panels, staging environments, or private sections of your site, this configuration adds an essential layer of protection.
6 - How to Use CGI Scripts with Nginx on AlmaLinux
CGI (Common Gateway Interface) scripts are one of the earliest and simplest ways to generate dynamic content on a web server. They allow a server to execute scripts (written in languages like Python, Perl, or Bash) and send the output to a user’s browser. Although CGI scripts are less common in modern development due to alternatives like PHP, FastCGI, and application frameworks, they remain useful for specific use cases such as small-scale web tools or legacy systems.
Nginx, a high-performance web server, does not natively support CGI scripts like Apache. However, with the help of additional tools such as FCGIWrapper or Spawn-FCGI, you can integrate CGI support into your Nginx server. This guide will walk you through the process of using CGI scripts with Nginx on AlmaLinux.
What are CGI Scripts?
A CGI script is a program that runs on a server in response to a user request, typically via an HTML form or direct URL. The script processes the request, generates output (usually in HTML), and sends it back to the client. CGI scripts can be written in any language that can produce standard output, including:
- Python
- Perl
- Bash
- C/C++
Prerequisites
Before you begin, ensure you have the following:
- AlmaLinux server with root or sudo privileges.
- Nginx installed and running.
- Basic knowledge of Linux commands and file permissions.
- CGI script(s) for testing, or the ability to create one.
Step-by-Step Guide to Using CGI Scripts with Nginx
Step 1: Update Your System
Begin by updating the AlmaLinux system to ensure you have the latest packages and security patches:
sudo dnf update -y
Step 2: Install Nginx (If Not Already Installed)
If Nginx is not installed, you can install it using:
sudo dnf install nginx -y
Start and enable the Nginx service:
sudo systemctl enable nginx
sudo systemctl start nginx
Step 3: Install and Configure a CGI Processor
Nginx does not natively support CGI scripts. To enable this functionality, you need a FastCGI wrapper or similar tool. For this guide, we’ll use fcgiwrap, a lightweight FastCGI server for handling CGI scripts.
Install
fcgiwrap
:sudo dnf install fcgiwrap -y
Enable and Start
fcgiwrap
:By default,
fcgiwrap
is managed by a systemd socket. Start and enable it:sudo systemctl enable fcgiwrap.socket sudo systemctl start fcgiwrap.socket
Check the status to ensure it’s running:
sudo systemctl status fcgiwrap.socket
Step 4: Set Up the CGI Script Directory
Create a directory to store your CGI scripts. The standard location for CGI scripts is /usr/lib/cgi-bin
, but you can use any directory.
sudo mkdir -p /usr/lib/cgi-bin
Set appropriate permissions for the directory:
sudo chmod 755 /usr/lib/cgi-bin
Add a test CGI script, such as a simple Bash script:
sudo nano /usr/lib/cgi-bin/hello.sh
Add the following code:
#!/bin/bash
echo "Content-type: text/html"
echo ""
echo "<html><body><h1>Hello from CGI!</h1></body></html>"
Save the file and make it executable:
sudo chmod +x /usr/lib/cgi-bin/hello.sh
Step 5: Configure Nginx for CGI Scripts
Edit the Nginx configuration to enable FastCGI processing for the /cgi-bin/
directory.
Edit the Nginx configuration:
Open the server block configuration file, typically located in
/etc/nginx/conf.d/
or/etc/nginx/nginx.conf
.sudo nano /etc/nginx/conf.d/default.conf
Add a location block for CGI scripts:
Add the following to the
server
block:server { listen 80; server_name your-domain.com; location /cgi-bin/ { root /usr/lib/; fastcgi_pass unix:/var/run/fcgiwrap.socket; include fastcgi_params; fastcgi_param SCRIPT_FILENAME /usr/lib$fastcgi_script_name; fastcgi_param QUERY_STRING $query_string; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; } }
Save and exit the configuration file.
Test the configuration:
Check for syntax errors:
sudo nginx -t
Reload Nginx:
Apply the changes by reloading the service:
sudo systemctl reload nginx
Step 6: Test the CGI Script
Open a browser and navigate to:
http://your-domain.com/cgi-bin/hello.sh
You should see the output: “Hello from CGI!”
Advanced Configuration
1. Restrict Access to CGI Scripts
If you only want specific users or IP addresses to access the /cgi-bin/
directory, you can restrict it using access control directives:
location /cgi-bin/ {
root /usr/lib/;
fastcgi_pass unix:/var/run/fcgiwrap.socket;
include fastcgi_params;
allow 192.168.1.0/24;
deny all;
}
2. Enable HTTPS for Secure Transmission
To ensure secure transmission of data to and from the CGI scripts, configure HTTPS using Let’s Encrypt:
Install Certbot:
sudo dnf install certbot python3-certbot-nginx -y
Obtain and configure an SSL certificate:
sudo certbot --nginx -d your-domain.com -d www.your-domain.com
Verify HTTPS functionality by accessing your CGI script over
https://
.
3. Debugging and Logs
Check Nginx Logs: Errors and access logs are stored in
/var/log/nginx/
. Use the following commands to view logs:sudo tail -f /var/log/nginx/error.log sudo tail -f /var/log/nginx/access.log
Check fcgiwrap Logs: If
fcgiwrap
fails, check its logs for errors:sudo journalctl -u fcgiwrap
Security Best Practices
Script Permissions: Ensure all CGI scripts have secure permissions. For example:
sudo chmod 700 /usr/lib/cgi-bin/*
Validate Input: Always validate and sanitize input to prevent injection attacks.
Restrict Execution: Limit script execution to trusted users or IP addresses using Nginx access control rules.
Use HTTPS: Encrypt all traffic with HTTPS to protect sensitive data.
Conclusion
Using CGI scripts with Nginx on AlmaLinux allows you to execute server-side scripts efficiently while maintaining Nginx’s high performance. With the help of tools like fcgiwrap
, you can integrate legacy CGI functionality into modern Nginx deployments. By following the steps in this guide, you can set up and test CGI scripts on your AlmaLinux server while ensuring security and scalability.
Whether for small-scale tools, testing environments, or legacy support, this setup provides a robust way to harness the power of CGI with Nginx.
7 - How to Use PHP Scripts with Nginx on AlmaLinux
PHP remains one of the most popular server-side scripting languages, powering millions of websites and applications worldwide. When combined with Nginx, a high-performance web server, PHP scripts can be executed efficiently to deliver dynamic web content. AlmaLinux, a CentOS alternative built for stability and security, is an excellent foundation for hosting PHP-based websites and applications.
In this comprehensive guide, we will explore how to set up and use PHP scripts with Nginx on AlmaLinux. By the end, you’ll have a fully functional Nginx-PHP setup capable of serving PHP applications like WordPress, Laravel, or custom scripts.
Prerequisites
Before diving into the setup, ensure you meet the following prerequisites:
- AlmaLinux server with sudo/root access.
- Nginx installed and running.
- Familiarity with the Linux command line.
- A domain name (optional) or the server’s IP address for testing.
Step-by-Step Guide to Using PHP Scripts with Nginx on AlmaLinux
Step 1: Update Your AlmaLinux System
Start by updating the system packages to ensure the latest software versions and security patches:
sudo dnf update -y
Step 2: Install Nginx (If Not Installed)
If Nginx isn’t already installed, you can install it using:
sudo dnf install nginx -y
Once installed, start and enable the Nginx service:
sudo systemctl start nginx
sudo systemctl enable nginx
Verify that Nginx is running by visiting your server’s IP address or domain in a web browser. The default Nginx welcome page should appear.
Step 3: Install PHP and PHP-FPM
Nginx doesn’t process PHP scripts directly; instead, it relies on a FastCGI Process Manager (PHP-FPM) to handle PHP execution. Install PHP and PHP-FPM with the following command:
sudo dnf install php php-fpm php-cli php-mysqlnd -y
php-fpm
: Handles PHP script execution.php-cli
: Allows running PHP scripts from the command line.php-mysqlnd
: Adds MySQL support for PHP (useful for applications like WordPress).
Step 4: Configure PHP-FPM
Open the PHP-FPM configuration file:
sudo nano /etc/php-fpm.d/www.conf
Look for the following lines and make sure they are set as shown:
user = nginx group = nginx listen = /run/php-fpm/www.sock listen.owner = nginx listen.group = nginx
- This configuration ensures PHP-FPM uses a Unix socket (
/run/php-fpm/www.sock
) for communication with Nginx.
- This configuration ensures PHP-FPM uses a Unix socket (
Save and exit the file, then restart PHP-FPM to apply the changes:
sudo systemctl restart php-fpm sudo systemctl enable php-fpm
Step 5: Configure Nginx to Use PHP
Now, you need to tell Nginx to pass PHP scripts to PHP-FPM for processing.
Open the Nginx server block configuration file. For the default site, edit:
sudo nano /etc/nginx/conf.d/default.conf
Modify the server block to include the following:
server { listen 80; server_name your-domain.com www.your-domain.com; # Replace with your domain or server IP root /var/www/html; index index.php index.html index.htm; location / { try_files $uri $uri/ =404; } location ~ \.php$ { include fastcgi_params; fastcgi_pass unix:/run/php-fpm/www.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } location ~ /\.ht { deny all; } }
fastcgi_pass
: Points to the PHP-FPM socket.fastcgi_param SCRIPT_FILENAME
: Tells PHP-FPM the full path of the script to execute.
Save and exit the file, then test the Nginx configuration:
sudo nginx -t
If the test is successful, reload Nginx:
sudo systemctl reload nginx
Step 6: Add a Test PHP Script
Create a test PHP file to verify the setup:
Navigate to the web root directory:
sudo mkdir -p /var/www/html
Create a
info.php
file:sudo nano /var/www/html/info.php
Add the following content:
<?php phpinfo(); ?>
Save and exit the file, then adjust permissions to ensure Nginx can read the file:
sudo chown -R nginx:nginx /var/www/html sudo chmod -R 755 /var/www/html
Step 7: Test PHP Configuration
Open a browser and navigate to:
http://your-domain.com/info.php
You should see a PHP information page displaying details about your PHP installation, server environment, and modules.
Securing Your Setup
1. Remove the info.php
File
The info.php
file exposes sensitive information about your server and PHP setup. Remove it after verifying your configuration:
sudo rm /var/www/html/info.php
2. Enable HTTPS
To secure your website, configure HTTPS using Let’s Encrypt. Install Certbot:
sudo dnf install certbot python3-certbot-nginx -y
Run Certbot to obtain and configure an SSL certificate:
sudo certbot --nginx -d your-domain.com -d www.your-domain.com
Certbot will automatically set up HTTPS in your Nginx configuration.
3. Restrict File Access
Prevent access to sensitive files like .env
or .htaccess
by adding rules in your Nginx configuration:
location ~ /\.(?!well-known).* {
deny all;
}
4. Optimize PHP Settings
To improve performance and security, edit the PHP configuration file:
sudo nano /etc/php.ini
- Set
display_errors = Off
to prevent error messages from showing on the frontend. - Adjust
upload_max_filesize
andpost_max_size
for file uploads, if needed. - Set a reasonable value for
max_execution_time
to avoid long-running scripts.
Restart PHP-FPM to apply changes:
sudo systemctl restart php-fpm
Troubleshooting Common Issues
1. PHP Not Executing, Showing as Plain Text
Ensure the
location ~ \.php$
block is correctly configured in your Nginx file.Check that PHP-FPM is running:
sudo systemctl status php-fpm
2. Nginx Fails to Start or Reload
Test the configuration for syntax errors:
sudo nginx -t
Check the logs for details:
sudo tail -f /var/log/nginx/error.log
3. 403 Forbidden Error
- Ensure the PHP script and its directory have the correct ownership and permissions.
- Verify the
root
directive in your Nginx configuration points to the correct directory.
Conclusion
Using PHP scripts with Nginx on AlmaLinux provides a powerful, efficient, and flexible setup for hosting dynamic websites and applications. By combining Nginx’s high performance with PHP’s versatility, you can run everything from simple scripts to complex frameworks like WordPress, Laravel, or Symfony.
With proper configuration, security measures, and optimization, your server will be ready to handle PHP-based applications reliably and efficiently. Whether you’re running a personal blog or a business-critical application, this guide provides the foundation for a robust PHP-Nginx setup on AlmaLinux.
8 - How to Set Up Nginx as a Reverse Proxy on AlmaLinux
A reverse proxy is a server that sits between clients and backend servers, forwarding client requests to the appropriate backend server and returning the server’s response to the client. Nginx, a high-performance web server, is a popular choice for setting up reverse proxies due to its speed, scalability, and flexibility.
In this guide, we’ll cover how to configure Nginx as a reverse proxy on AlmaLinux. This setup is particularly useful for load balancing, improving security, caching, or managing traffic for multiple backend services.
What is a Reverse Proxy?
A reverse proxy acts as an intermediary for client requests, forwarding them to backend servers. Unlike a forward proxy that shields clients from servers, a reverse proxy shields servers from clients. Key benefits include:
- Load Balancing: Distributes incoming requests across multiple servers to ensure high availability.
- Enhanced Security: Hides backend server details and acts as a buffer for malicious traffic.
- SSL Termination: Offloads SSL/TLS encryption to the reverse proxy to reduce backend server load.
- Caching: Improves performance by caching responses.
Prerequisites
Before setting up Nginx as a reverse proxy, ensure you have the following:
- AlmaLinux server with root or sudo privileges.
- Nginx installed and running.
- One or more backend servers to proxy traffic to. These could be applications running on different ports of the same server or separate servers entirely.
- A domain name (optional) pointed to your Nginx server for easier testing.
Step-by-Step Guide to Configuring Nginx as a Reverse Proxy
Step 1: Update Your AlmaLinux System
Update all packages to ensure your system is up-to-date:
sudo dnf update -y
Step 2: Install Nginx
If Nginx isn’t installed, you can install it with:
sudo dnf install nginx -y
Start and enable Nginx:
sudo systemctl start nginx
sudo systemctl enable nginx
Verify the installation by visiting your server’s IP address in a web browser. The default Nginx welcome page should appear.
Step 3: Configure Backend Servers
For demonstration purposes, let’s assume you have two backend services:
- Backend 1: A web application running on
http://127.0.0.1:8080
- Backend 2: Another service running on
http://127.0.0.1:8081
Ensure these services are running. You can use simple HTTP servers like Python’s built-in HTTP server for testing:
# Start a simple server on port 8080
python3 -m http.server 8080
# Start another server on port 8081
python3 -m http.server 8081
Step 4: Create a Reverse Proxy Configuration
Edit the Nginx configuration file:
Create a new configuration file in
/etc/nginx/conf.d/
. For example:sudo nano /etc/nginx/conf.d/reverse-proxy.conf
Add the reverse proxy configuration:
Here’s an example configuration to proxy traffic for two backend services:
server { listen 80; server_name your-domain.com; location /app1/ { proxy_pass http://127.0.0.1:8080/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } location /app2/ { proxy_pass http://127.0.0.1:8081/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
proxy_pass
: Specifies the backend server for the location.proxy_set_header
: Passes client information (e.g., IP address) to the backend server.
Save and exit the file.
Step 5: Test and Reload Nginx Configuration
Test the configuration for syntax errors:
sudo nginx -t
Reload Nginx to apply the changes:
sudo systemctl reload nginx
Step 6: Test the Reverse Proxy
Open a browser and test the setup:
http://your-domain.com/app1/
should proxy to the service running on port8080
.http://your-domain.com/app2/
should proxy to the service running on port8081
.
Enhancing the Reverse Proxy Setup
1. Add SSL/TLS with Let’s Encrypt
Securing your reverse proxy with SSL/TLS is crucial for protecting client data. Use Certbot to obtain and configure an SSL certificate:
Install Certbot:
sudo dnf install certbot python3-certbot-nginx -y
Obtain an SSL certificate for your domain:
sudo certbot --nginx -d your-domain.com
Certbot will automatically configure SSL for your reverse proxy. Test it by accessing:
https://your-domain.com/app1/
https://your-domain.com/app2/
2. Load Balancing Backend Servers
If you have multiple instances of a backend service, Nginx can distribute traffic across them. Modify the proxy_pass
directive to include an upstream block:
Define an upstream group in the Nginx configuration:
upstream app1_backend { server 127.0.0.1:8080; server 127.0.0.1:8082; # Additional instance }
Update the
proxy_pass
directive to use the upstream group:location /app1/ { proxy_pass http://app1_backend/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; }
3. Enable Caching for Static Content
To improve performance, enable caching for static content like images, CSS, and JavaScript files:
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2|ttf|otf|eot|svg)$ {
expires max;
log_not_found off;
add_header Cache-Control "public";
}
4. Restrict Access to Backend Servers
To prevent direct access to your backend servers, use firewall rules to restrict access. For example, allow only Nginx to access the backend ports:
sudo firewall-cmd --add-rich-rule='rule family="ipv4" source address="127.0.0.1" port port="8080" protocol="tcp" accept' --permanent
sudo firewall-cmd --add-rich-rule='rule family="ipv4" source address="127.0.0.1" port port="8081" protocol="tcp" accept' --permanent
sudo firewall-cmd --reload
Troubleshooting
1. 502 Bad Gateway Error
Ensure the backend service is running.
Verify the
proxy_pass
URL is correct.Check the Nginx error log for details:
sudo tail -f /var/log/nginx/error.log
2. Configuration Fails to Reload
Test the configuration for syntax errors:
sudo nginx -t
Correct any issues before reloading.
3. SSL Not Working
- Ensure Certbot successfully obtained a certificate.
- Check the Nginx error log for SSL-related issues.
Conclusion
Using Nginx as a reverse proxy on AlmaLinux is a powerful way to manage and optimize traffic between clients and backend servers. By following this guide, you’ve set up a robust reverse proxy configuration, with the flexibility to scale, secure, and enhance your web applications. Whether for load balancing, caching, or improving security, Nginx provides a reliable foundation for modern server management.
9 - How to Set Up Nginx Load Balancing on AlmaLinux
As modern web applications grow in complexity and user base, ensuring high availability and scalability becomes crucial. Load balancing is a technique that distributes incoming traffic across multiple servers to prevent overloading a single machine, ensuring better performance and reliability. Nginx, known for its high performance and flexibility, offers robust load-balancing features, making it an excellent choice for managing traffic for web applications.
In this guide, we’ll walk you through how to set up and configure load balancing with Nginx on AlmaLinux. By the end, you’ll have a scalable and efficient solution for handling increased traffic to your web services.
What is Load Balancing?
Load balancing is the process of distributing incoming requests across multiple backend servers, also known as upstream servers. This prevents any single server from being overwhelmed and ensures that traffic is handled efficiently.
Benefits of Load Balancing
- Improved Performance: Distributes traffic across servers to reduce response times.
- High Availability: If one server fails, traffic is redirected to other available servers.
- Scalability: Add or remove servers as needed without downtime.
- Fault Tolerance: Ensures the application remains operational even if individual servers fail.
Prerequisites
Before starting, ensure you have:
- AlmaLinux server with sudo/root privileges.
- Nginx installed and running.
- Two or more backend servers or services to distribute traffic.
- Basic knowledge of Linux command-line operations.
Step-by-Step Guide to Setting Up Nginx Load Balancing
Step 1: Update Your AlmaLinux System
Ensure your AlmaLinux server is up-to-date with the latest packages and security patches:
sudo dnf update -y
Step 2: Install Nginx
If Nginx is not already installed, you can install it using:
sudo dnf install nginx -y
Enable and start Nginx:
sudo systemctl enable nginx
sudo systemctl start nginx
Verify Nginx is running by visiting your server’s IP address in a web browser. The default Nginx welcome page should appear.
Step 3: Set Up Backend Servers
To demonstrate load balancing, we’ll use two simple backend servers. These servers can run on different ports of the same machine or on separate machines.
For testing, you can use Python’s built-in HTTP server:
# Start a test server on port 8080
python3 -m http.server 8080
# Start another test server on port 8081
python3 -m http.server 8081
Ensure these backend servers are running and accessible. You can check by visiting:
http://<your-server-ip>:8080
http://<your-server-ip>:8081
Step 4: Configure Nginx for Load Balancing
Create an Upstream Block: The upstream block defines the backend servers that will handle incoming traffic.
Open a new configuration file:
sudo nano /etc/nginx/conf.d/load_balancer.conf
Add the following:
upstream backend_servers { server 127.0.0.1:8080; server 127.0.0.1:8081; } server { listen 80; server_name your-domain.com; location / { proxy_pass http://backend_servers; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } }
upstream
block: Lists the backend servers.proxy_pass
: Forwards requests to the upstream block.proxy_set_header
: Passes client information to the backend servers.
Save and exit the file.
Step 5: Test and Reload Nginx
Check the configuration for syntax errors:
sudo nginx -t
Reload Nginx to apply the changes:
sudo systemctl reload nginx
Step 6: Test Load Balancing
Visit your domain or server IP in a browser:
http://your-domain.com
Refresh the page multiple times. You should see responses from both backend servers alternately.
Load Balancing Methods in Nginx
Nginx supports several load-balancing methods:
1. Round Robin (Default)
The default method, where requests are distributed sequentially to each server.
upstream backend_servers {
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}
2. Least Connections
Directs traffic to the server with the fewest active connections. Ideal for servers with varying response times.
upstream backend_servers {
least_conn;
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}
3. IP Hash
Routes requests from the same client IP to the same backend server. Useful for session persistence.
upstream backend_servers {
ip_hash;
server 127.0.0.1:8080;
server 127.0.0.1:8081;
}
Advanced Configuration Options
1. Configure Health Checks
To automatically remove unhealthy servers from the rotation, you can use third-party Nginx modules or advanced configurations.
Example with max_fails
and fail_timeout
:
upstream backend_servers {
server 127.0.0.1:8080 max_fails=3 fail_timeout=30s;
server 127.0.0.1:8081 max_fails=3 fail_timeout=30s;
}
2. Enable SSL/TLS for Secure Traffic
Secure your load balancer by configuring HTTPS with Let’s Encrypt.
Install Certbot:
sudo dnf install certbot python3-certbot-nginx -y
Obtain and configure an SSL certificate:
sudo certbot --nginx -d your-domain.com
3. Caching Responses
To improve performance, you can enable caching for responses from backend servers:
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=cache_zone:10m inactive=60m;
proxy_cache_key "$scheme$request_method$host$request_uri";
server {
location / {
proxy_cache cache_zone;
proxy_pass http://backend_servers;
proxy_set_header Host $host;
}
}
Troubleshooting
1. 502 Bad Gateway Error
Verify that backend servers are running and accessible.
Check the
proxy_pass
URL in the configuration.Review the Nginx error log:
sudo tail -f /var/log/nginx/error.log
2. Nginx Fails to Start or Reload
Test the configuration for syntax errors:
sudo nginx -t
Check logs for details:
sudo journalctl -xe
3. Backend Servers Not Rotating
- Ensure the backend servers are listed correctly in the
upstream
block. - Test different load-balancing methods.
Conclusion
Setting up load balancing with Nginx on AlmaLinux provides a scalable and efficient solution for handling increased traffic to your web applications. With features like round-robin distribution, least connections, and IP hashing, Nginx allows you to customize traffic management based on your application needs.
By following this guide, you’ve configured a robust load balancer, complete with options for secure connections and advanced optimizations. Whether you’re managing a small application or a high-traffic website, Nginx’s load-balancing capabilities are a reliable foundation for ensuring performance and availability.
10 - How to Use the Stream Module with Nginx on AlmaLinux
Nginx is widely known as a high-performance HTTP and reverse proxy server. However, its capabilities extend beyond just HTTP; it also supports other network protocols such as TCP and UDP. The Stream module in Nginx is specifically designed to handle these non-HTTP protocols, allowing Nginx to act as a load balancer or proxy for applications like databases, mail servers, game servers, or custom network applications.
In this guide, we’ll explore how to enable and configure the Stream module with Nginx on AlmaLinux. By the end of this guide, you’ll know how to proxy and load balance TCP/UDP traffic effectively using Nginx.
What is the Stream Module?
The Stream module is a core Nginx module that enables handling of TCP and UDP traffic. It supports:
- Proxying: Forwarding TCP/UDP requests to a backend server.
- Load Balancing: Distributing traffic across multiple backend servers.
- SSL/TLS Termination: Offloading encryption/decryption for secure traffic.
- Traffic Filtering: Filtering traffic by IP or rate-limiting connections.
Common use cases include:
- Proxying database connections (e.g., MySQL, PostgreSQL).
- Load balancing game servers.
- Proxying mail servers (e.g., SMTP, IMAP, POP3).
- Managing custom TCP/UDP applications.
Prerequisites
- AlmaLinux server with sudo privileges.
- Nginx installed (compiled with the Stream module).
- At least one TCP/UDP service to proxy (e.g., a database, game server, or custom application).
Step-by-Step Guide to Using the Stream Module
Step 1: Update the System
Begin by ensuring your AlmaLinux system is up-to-date:
sudo dnf update -y
Step 2: Check for Stream Module Support
The Stream module is typically included in the default Nginx installation on AlmaLinux. To verify:
Check the available Nginx modules:
nginx -V
Look for
--with-stream
in the output. If it’s present, the Stream module is already included. If not, you’ll need to install or build Nginx with Stream support (covered in Appendix).
Step 3: Enable the Stream Module
By default, the Stream module configuration is separate from the HTTP configuration. You need to enable and configure it.
Create the Stream configuration directory:
sudo mkdir -p /etc/nginx/stream.d
Edit the main Nginx configuration file:
Open
/etc/nginx/nginx.conf
:sudo nano /etc/nginx/nginx.conf
Add the following within the main configuration block:
stream { include /etc/nginx/stream.d/*.conf; }
This directive tells Nginx to include all Stream-related configurations from
/etc/nginx/stream.d/
.
Step 4: Configure TCP/UDP Proxying
Create a new configuration file for your Stream module setup. For example:
sudo nano /etc/nginx/stream.d/tcp_proxy.conf
Example 1: Simple TCP Proxy
This configuration proxies incoming TCP traffic on port 3306 to a MySQL backend server:
server {
listen 3306;
proxy_pass 192.168.1.10:3306;
}
listen
: Specifies the port Nginx listens on for incoming TCP connections.proxy_pass
: Defines the backend server address and port.
Example 2: Simple UDP Proxy
For a UDP-based application (e.g., DNS server):
server {
listen 53 udp;
proxy_pass 192.168.1.20:53;
}
- The
udp
flag tells Nginx to handle UDP traffic.
Save and close the file after adding the configuration.
Step 5: Test and Reload Nginx
Test the Nginx configuration:
sudo nginx -t
Reload Nginx to apply the changes:
sudo systemctl reload nginx
Step 6: Test the Proxy
For TCP, use a tool like telnet or a database client to connect to the proxied service via the Nginx server.
Example for MySQL:
mysql -u username -h nginx-server-ip -p
For UDP, use dig or a similar tool to test the connection:
dig @nginx-server-ip example.com
Advanced Configuration
Load Balancing with the Stream Module
The Stream module supports load balancing across multiple backend servers. Use the upstream
directive to define a group of backend servers.
Example: Load Balancing TCP Traffic
Distribute MySQL traffic across multiple servers:
upstream mysql_cluster {
server 192.168.1.10:3306;
server 192.168.1.11:3306;
server 192.168.1.12:3306;
}
server {
listen 3306;
proxy_pass mysql_cluster;
}
Example: Load Balancing UDP Traffic
Distribute DNS traffic across multiple servers:
upstream dns_servers {
server 192.168.1.20:53;
server 192.168.1.21:53;
}
server {
listen 53 udp;
proxy_pass dns_servers;
}
Session Persistence
For TCP-based applications like databases, session persistence ensures that clients are always routed to the same backend server. Add the hash
directive:
upstream mysql_cluster {
hash $remote_addr consistent;
server 192.168.1.10:3306;
server 192.168.1.11:3306;
}
hash $remote_addr consistent
: Routes traffic based on the client’s IP address.
SSL/TLS Termination
To secure traffic, you can terminate SSL/TLS connections at the Nginx server:
server {
listen 443 ssl;
proxy_pass 192.168.1.10:3306;
ssl_certificate /etc/nginx/ssl/server.crt;
ssl_certificate_key /etc/nginx/ssl/server.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
}
- Replace
/etc/nginx/ssl/server.crt
and/etc/nginx/ssl/server.key
with your SSL certificate and private key paths.
Traffic Filtering
To restrict traffic based on IP or apply rate limiting:
Example: Allow/Deny Specific IPs
server {
listen 3306;
proxy_pass 192.168.1.10:3306;
allow 192.168.1.0/24;
deny all;
}
Example: Rate Limiting Connections
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
listen 3306;
proxy_pass 192.168.1.10:3306;
limit_conn conn_limit 10;
}
limit_conn_zone
: Defines the shared memory zone for tracking connections.limit_conn
: Limits connections per client.
Troubleshooting
1. Stream Configuration Not Working
- Ensure the
stream
block is included in the mainnginx.conf
file. - Verify the configuration with
nginx -t
.
2. 502 Bad Gateway Errors
- Check if the backend servers are running and accessible.
- Verify the
proxy_pass
addresses.
3. Nginx Fails to Reload
- Check for syntax errors using
nginx -t
. - Review error logs at
/var/log/nginx/error.log
.
Conclusion
The Nginx Stream module offers powerful features for managing TCP and UDP traffic, making it an invaluable tool for modern networked applications. Whether you need simple proxying, advanced load balancing, or secure SSL termination, the Stream module provides a flexible and performant solution.
By following this guide, you’ve learned how to enable and configure the Stream module on AlmaLinux. With advanced configurations like load balancing, session persistence, and traffic filtering, your Nginx server is ready to handle even the most demanding TCP/UDP workloads.