AlmaLinuxRHEL Based

How To Set Up Nginx Server Blocks on AlmaLinux 10

Set Up Nginx Server Blocks on AlmaLinux 10

Nginx server blocks represent one of the most powerful features for hosting multiple websites on a single AlmaLinux 10 server. Server blocks, similar to Apache’s virtual hosts, enable you to configure separate domains with distinct settings, allowing efficient resource utilization and streamlined web hosting management. This comprehensive guide walks you through the complete process of setting up Nginx server blocks on AlmaLinux 10, from initial installation to advanced configuration optimization.

Prerequisites and System Requirements

Before beginning the server block configuration process, ensure your AlmaLinux 10 system meets the following requirements:

System Requirements

Your AlmaLinux 10 server should have minimum 1GB RAM and 20GB disk space for optimal performance. A stable network connection and properly configured DNS records are essential for domain resolution. Additionally, you’ll need root or sudo privileges to execute administrative commands throughout this guide.

Domain Configuration Requirements

Proper DNS A records must point your domain names to your server’s public IP address. This DNS configuration ensures that web browsers can locate your server when users access your domains. Consider setting up both the primary domain and www subdomain variants for comprehensive coverage.

Installing Nginx on AlmaLinux 10

Updating System Packages

Begin by updating your AlmaLinux 10 system to ensure you have the latest security patches and package versions:

sudo dnf update -y

This command updates all installed packages and their dependencies, providing a stable foundation for Nginx installation.

Installing Nginx via DNF Package Manager

AlmaLinux 10 includes Nginx in the EPEL (Extra Packages for Enterprise Linux) repository. First, enable the EPEL repository:

sudo dnf install epel-release -y

Next, install Nginx using the DNF package manager:

sudo dnf install nginx -y

Verify the installation by checking the Nginx version:

nginx -v

This command should display the installed Nginx version, confirming successful installation.

Starting and Enabling Nginx Service

Start the Nginx service immediately:

sudo systemctl start nginx

Enable Nginx to start automatically during system boot:

sudo systemctl enable nginx

Verify the service status:

sudo systemctl status nginx

The output should show Nginx as active (running), indicating successful service initialization.

Firewall Configuration for Web Traffic

Opening HTTP and HTTPS Ports

AlmaLinux 10’s firewall blocks web traffic by default. Configure the firewall to allow HTTP and HTTPS connections:

sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload

Verify the firewall configuration:

sudo firewall-cmd --list-all

You should see both http and https listed under the services section.

Testing Initial Nginx Installation

Open a web browser and navigate to your server’s IP address:

http://your-server-ip

The default Nginx welcome page confirms successful installation and proper firewall configuration.

Understanding Server Blocks Architecture

Server blocks function as independent website configurations within a single Nginx installation. Each server block contains specific directives for handling requests to particular domains or subdomains. This architecture enables efficient resource sharing while maintaining separate configurations for different websites.

The key advantage of server blocks over traditional single-site configurations lies in their scalability and flexibility. You can host unlimited domains on a single server, each with customized settings for performance optimization, security policies, and content delivery.

Creating Document Root Directories

Establishing Directory Structure

Create organized directory structures for each domain you plan to host. This systematic approach simplifies file management and maintenance:

sudo mkdir -p /var/www/example.com/html
sudo mkdir -p /var/www/test.com/html

The -p flag ensures that parent directories are created if they don’t exist.

Setting Proper Permissions

Configure appropriate ownership and permissions for web directories:

sudo chown -R $USER:$USER /var/www/example.com/html
sudo chown -R $USER:$USER /var/www/test.com/html
sudo chmod -R 755 /var/www

These commands set the current user as the owner while maintaining read and execute permissions for the web server.

Creating Sample Index Files

Generate test content for each domain to verify server block functionality:

echo "<h1>Welcome to Example.com</h1><p>Server block is working correctly!</p>" > /var/www/example.com/html/index.html
echo "<h1>Welcome to Test.com</h1><p>Second server block is operational!</p>" > /var/www/test.com/html/index.html

These HTML files provide visual confirmation when testing your server block configuration.

Creating Server Block Configuration Files

Understanding Nginx Configuration Structure

Nginx stores server block configurations in the /etc/nginx/conf.d/ directory by default. This modular approach keeps configurations organized and maintainable. Each domain should have its own configuration file with a descriptive filename.

Basic Server Block Configuration

Create your first server block configuration file:

sudo nano /etc/nginx/conf.d/example.com.conf

Add the following configuration:

server {
    listen 80;
    listen [::]:80;
    
    server_name example.com www.example.com;
    root /var/www/example.com/html;
    index index.html index.htm index.nginx-debian.html;
    
    access_log /var/log/nginx/example.com_access.log;
    error_log /var/log/nginx/example.com_error.log;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

This configuration includes several essential directives:

  • listen: Specifies ports for HTTP traffic (80) and IPv6 support
  • server_name: Defines domains that trigger this server block
  • root: Sets the document root directory for website files
  • index: Specifies default files to serve for directory requests
  • access_log/error_log: Defines separate log files for monitoring
  • location /: Handles all incoming requests with file existence checking

Advanced Server Block Options

For enhanced functionality, consider adding these advanced directives:

server {
    listen 80;
    listen [::]:80;
    
    server_name example.com www.example.com;
    root /var/www/example.com/html;
    index index.html index.htm;
    
    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    
    # Gzip compression
    gzip on;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml;
    
    # Custom error pages
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;
    
    location / {
        try_files $uri $uri/ =404;
    }
    
    # Optimize static file serving
    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}

These advanced options improve security, performance, and user experience.

Testing and Validating Configuration

Nginx Configuration Syntax Testing

Before applying changes, always test your Nginx configuration for syntax errors:

sudo nginx -t

This command validates all configuration files and reports any syntax issues. A successful test displays:

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

Reloading Nginx Configuration

Apply configuration changes without interrupting active connections:

sudo systemctl reload nginx

The reload command gracefully updates the configuration while maintaining existing connections, unlike restart which terminates all active sessions.

Verifying Server Block Functionality

Test your server block by accessing your domain in a web browser:

http://example.com

You should see your custom HTML content, confirming that the server block is processing requests correctly.

Setting Up Multiple Server Blocks

Creating Additional Server Blocks

Copy your existing configuration as a template for additional domains:

sudo cp /etc/nginx/conf.d/example.com.conf /etc/nginx/conf.d/test.com.conf

Edit the new configuration file:

sudo nano /etc/nginx/conf.d/test.com.conf

Modify the relevant directives:

server {
    listen 80;
    listen [::]:80;
    
    server_name test.com www.test.com;
    root /var/www/test.com/html;
    index index.html index.htm;
    
    access_log /var/log/nginx/test.com_access.log;
    error_log /var/log/nginx/test.com_error.log;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

This approach ensures consistency while allowing customization for each domain.

Managing DNS Configuration

Ensure your DNS A records point to your server’s IP address:

example.com    A    192.168.1.100
www.example.com A   192.168.1.100
test.com       A    192.168.1.100
www.test.com   A    192.168.1.100

DNS propagation may take up to 24 hours globally, though changes typically appear within a few hours.

Server Block Priority and Default Handling

Nginx processes server blocks based on the server_name directive specificity. When multiple server blocks could match a request, Nginx uses the most specific match. Configure a default server block to handle unmatched requests:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    
    server_name _;
    root /var/www/html;
    
    return 444;  # Close connection without response
}

This configuration prevents unauthorized access attempts to your server.

SSL/HTTPS Configuration and Security

Installing SSL Certificates

Secure your websites with Let’s Encrypt SSL certificates. First, install Certbot:

sudo dnf install certbot python3-certbot-nginx -y

Obtain SSL certificates for your domains:

sudo certbot --nginx -d example.com -d www.example.com

Certbot automatically modifies your server block configuration to include SSL settings.

HTTPS Server Block Configuration

After SSL installation, your server block will include HTTPS configuration:

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    
    server_name example.com www.example.com;
    root /var/www/example.com/html;
    
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    
    # Security headers for HTTPS
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

# Redirect HTTP to HTTPS
server {
    listen 80;
    listen [::]:80;
    
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}

This configuration enforces HTTPS and includes essential security headers.

Troubleshooting Common Issues

Configuration Errors

Syntax errors are the most common issues when configuring server blocks. Always use nginx -t before applying changes. Common syntax problems include:

  • Missing semicolons after directives
  • Incorrect bracket placement
  • Invalid directive names or values
  • Conflicting listen directives across server blocks

Permission Issues

If you encounter 403 Forbidden errors, check directory permissions:

sudo chmod -R 755 /var/www/example.com/html
sudo chown -R nginx:nginx /var/www/example.com/html

Ensure the Nginx user can read your web files.

DNS Resolution Problems

When domains don’t resolve correctly, verify your DNS configuration:

dig example.com
nslookup example.com

For local testing, modify your /etc/hosts file:

192.168.1.100 example.com www.example.com

This bypasses DNS for testing purposes.

Port Conflicts

If Nginx fails to start due to port conflicts, identify processes using port 80:

sudo netstat -tlnp | grep :80
sudo lsof -i :80

Stop conflicting services or change Nginx listen ports as needed.

Monitoring and Performance Optimization

Log File Analysis

Monitor your server blocks through access and error logs:

sudo tail -f /var/log/nginx/example.com_access.log
sudo tail -f /var/log/nginx/example.com_error.log

Implement log rotation to manage disk space:

sudo logrotate /etc/logrotate.d/nginx

Performance Monitoring

Monitor Nginx performance using built-in status modules. Add the following to your server block:

location /nginx_status {
    stub_status on;
    access_log off;
    allow 127.0.0.1;
    deny all;
}

Access status information at http://example.com/nginx_status.

Optimization Techniques

Implement these performance optimizations:

# Worker process optimization
worker_processes auto;
worker_connections 1024;

# Gzip compression
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;

# File caching
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
    access_log off;
}

# Keep-alive connections
keepalive_timeout 65;
keepalive_requests 100;

These settings improve response times and resource utilization.

Advanced Configuration Topics

Reverse Proxy Setup

Configure Nginx as a reverse proxy for backend applications:

location /api {
    proxy_pass http://localhost:3000;
    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;
}

This configuration forwards API requests to a backend application server.

Load Balancing Configuration

Distribute traffic across multiple backend servers:

upstream backend {
    server 192.168.1.10:8080;
    server 192.168.1.11:8080;
    server 192.168.1.12:8080;
}

server {
    listen 80;
    server_name example.com;
    
    location / {
        proxy_pass http://backend;
    }
}

This setup provides high availability and improved performance.

Rate Limiting Implementation

Protect your server from abuse with rate limiting:

http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
    
    server {
        location / {
            limit_req zone=one burst=5;
        }
    }
}

This configuration limits requests to one per second per IP address.

Security Best Practices

Hiding Server Information

Prevent information disclosure by hiding the Nginx version:

server_tokens off;

Add this directive to your http block in the main configuration file.

Implementing Security Headers

Enhance security with comprehensive headers:

add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'" always;

These headers protect against common web vulnerabilities.

File Upload Security

Restrict file uploads and prevent execution:

client_max_body_size 10M;

location ~* \.(php|pl|py|jsp|asp|sh|cgi)$ {
    deny all;
}

This prevents potentially dangerous file uploads.

Congratulations! You have successfully set up Nginx server blocks. Thanks for using this tutorial to configure Nginx server blocks on your AlmaLinux OS 10 system. For additional or useful information, we recommend you check the official Nginx website.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button