FedoraRHEL Based

How To Setup Virtual Host Apache on Fedora 43

Setup Virtual Host Apache on Fedora 43

Hosting multiple websites on a single server doesn’t require separate physical machines or complex infrastructure. Apache virtual hosts provide an elegant solution that allows system administrators and web developers to run multiple domains from one server, reducing costs while maintaining complete control over each website’s configuration. This comprehensive guide walks you through the entire process of setting up Apache virtual hosts on Fedora 43, from initial installation to advanced configurations and troubleshooting.

Whether you’re managing a production web server or building a local development environment, understanding virtual host configuration is essential for modern web hosting. The process involves several key steps that work together to create isolated, functional web environments for each domain.

What Are Apache Virtual Hosts?

Apache virtual hosts represent a powerful feature that enables the Apache HTTP Server to host multiple websites or applications on a single physical server. Each virtual host operates independently with its own configuration, document root, and logging system, creating complete separation between different websites sharing the same hardware and IP address.

The technology primarily comes in two flavors: name-based and IP-based virtual hosting. Name-based virtual hosting relies on the HTTP Host header sent by the client’s browser to determine which website to serve, making it the most common and resource-efficient approach. IP-based virtual hosting assigns a unique IP address to each website, though this method is less common due to IPv4 address scarcity.

The benefits extend beyond simple cost savings. Virtual hosts enable better resource utilization, simplified management through centralized server administration, and the flexibility to test multiple sites in development environments. Organizations can run dozens of websites from a single well-configured server without sacrificing performance or security.

Prerequisites and Requirements

Before beginning the virtual host setup, ensure your system meets specific requirements. You’ll need a Fedora 43 installation with root or sudo privileges to execute administrative commands and modify system configurations.

Basic familiarity with the Linux command line is essential. You should be comfortable navigating the filesystem, editing text files using editors like nano or vim, and understanding basic file permissions. While domain names are ideal for production environments, you can use the local hosts file for testing purposes during development.

The server should have adequate resources based on your anticipated traffic and number of virtual hosts. A minimum of 1GB RAM and sufficient disk space for website files and logs will support most basic configurations. Ensure your firewall is accessible for configuration, as web traffic requires specific ports to be open.

Installing Apache on Fedora 43

Apache installation on Fedora 43 uses the DNF package manager, which handles dependencies automatically. Open your terminal and execute the installation command:

sudo dnf install httpd -y

The httpd package contains the core Apache HTTP Server components necessary for serving web content. The -y flag automatically confirms the installation, streamlining the process without prompting for user confirmation.

After successful installation, start the Apache service immediately:

sudo systemctl start httpd

Configure Apache to launch automatically at system boot, ensuring your websites remain accessible after server restarts:

sudo systemctl enable httpd

Alternatively, combine both operations with a single command:

sudo systemctl enable httpd --now

Verify the service is running correctly by checking its status:

sudo systemctl status httpd

A successful installation shows “active (running)” in green text. If you encounter any issues, the status output provides initial troubleshooting information.

Configuring Firewall Rules

Fedora 43 ships with firewalld active by default, blocking incoming web traffic until explicitly allowed. Web servers require two specific ports: port 80 for HTTP traffic and port 443 for HTTPS encrypted connections.

The recommended approach uses firewalld’s predefined service names, which automatically map to the correct ports:

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

The --permanent flag ensures these rules persist across system reboots. Apply the changes immediately by reloading the firewall:

sudo firewall-cmd --reload

Verify the firewall rules are active:

sudo firewall-cmd --list-all

You should see http and https listed under services. This confirms external clients can now connect to your web server.

SELinux, Fedora’s mandatory access control system, may also require attention. Apache needs appropriate SELinux contexts to serve files from custom directories, though default paths typically work without modification.

Testing Default Apache Installation

Before configuring virtual hosts, confirm Apache is functioning correctly. Open a web browser and navigate to your server’s IP address:

http://your-server-ip

The default Apache test page should appear, displaying “Fedora Test Page” or similar content. This confirms Apache is receiving and responding to HTTP requests.

Apache’s default configuration uses /var/www/html as the document root directory, where website files are stored. The main configuration file resides at /etc/httpd/conf/httpd.conf, containing global settings that apply to all virtual hosts unless overridden.

Additional configuration files are stored in /etc/httpd/conf.d/, where you’ll create your virtual host configurations. This modular approach separates custom configurations from default settings, preventing package updates from overwriting your modifications.

Creating Directory Structure for Virtual Hosts

Organized directory structures simplify management and troubleshooting. Create separate directories for each virtual host, establishing clear boundaries between different websites.

For your first virtual host:

sudo mkdir -p /var/www/example1.com/public_html

The -p flag creates parent directories as needed. The public_html subdirectory follows web hosting conventions, clearly identifying web-accessible content.

Create a second virtual host directory using the same pattern:

sudo mkdir -p /var/www/example2.com/public_html

This hierarchical structure supports additional subdirectories for logs, configuration files, or private data that shouldn’t be web-accessible. Many administrators create separate logs directories within each virtual host folder for organizational purposes.

The structure scales efficiently as you add more virtual hosts. Each domain receives its own isolated directory tree, preventing file conflicts and simplifying backup procedures.

Setting Proper Permissions and Ownership

File permissions and ownership determine whether Apache can read and serve your website files. The Apache process runs as the apache user on Fedora systems, requiring read access to all served content.

Set ownership for the first virtual host:

sudo chown -R apache:apache /var/www/example1.com

The -R flag applies changes recursively to all subdirectories and files. This ensures Apache owns the entire directory tree.

Configure appropriate permissions:

sudo chmod -R 755 /var/www/example1.com

The 755 permission mode grants read, write, and execute permissions to the owner (apache), while others receive only read and execute access. This balances functionality with security.

Repeat these commands for all virtual host directories:

sudo chown -R apache:apache /var/www/example2.com
sudo chmod -R 755 /var/www/example2.com

Never use 777 permissions in production environments. This grants write access to everyone, creating severe security vulnerabilities.

Creating Sample Website Content

Test your virtual host configuration with simple HTML files that clearly identify each website. Create an index file for the first virtual host:

sudo nano /var/www/example1.com/public_html/index.html

Add distinctive HTML content:

<!DOCTYPE html>
<html>
<head>
    <title>Welcome to Example1.com</title>
</head>
<body>
    <h1>Success! Example1.com Virtual Host is Working</h1>
    <p>This is the example1.com virtual host.</p>
</body>
</html>

Create a different index file for the second virtual host to distinguish between them during testing:

sudo nano /var/www/example2.com/public_html/index.html
<!DOCTYPE html>
<html>
<head>
    <title>Welcome to Example2.com</title>
</head>
<body>
    <h1>Success! Example2.com Virtual Host is Working</h1>
    <p>This is the example2.com virtual host.</p>
</body>
</html>

These test pages immediately confirm whether Apache is serving the correct content for each domain.

Creating Virtual Host Configuration Files

Apache on Fedora stores virtual host configurations in /etc/httpd/conf.d/, where any file ending in .conf is automatically loaded. Create a configuration file for your first virtual host:

sudo nano /etc/httpd/conf.d/example1.com.conf

Add the complete virtual host configuration:

<VirtualHost *:80>
    ServerName example1.com
    ServerAlias www.example1.com
    ServerAdmin webmaster@example1.com
    DocumentRoot /var/www/example1.com/public_html
    
    <Directory /var/www/example1.com/public_html>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>
    
    ErrorLog /var/log/httpd/example1.com-error.log
    CustomLog /var/log/httpd/example1.com-access.log combined
</VirtualHost>

Each directive serves a specific purpose in the configuration. The <VirtualHost *:80> tag indicates this virtual host responds to requests on port 80 for any IP address assigned to the server.

Create a second virtual host configuration:

sudo nano /etc/httpd/conf.d/example2.com.conf
<VirtualHost *:80>
    ServerName example2.com
    ServerAlias www.example2.com
    ServerAdmin webmaster@example2.com
    DocumentRoot /var/www/example2.com/public_html
    
    <Directory /var/www/example2.com/public_html>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>
    
    ErrorLog /var/log/httpd/example2.com-error.log
    CustomLog /var/log/httpd/example2.com-access.log combined
</VirtualHost>

Naming configuration files after their domain simplifies identification and management as your server grows.

Understanding Virtual Host Directives

The ServerName directive specifies the primary hostname for the virtual host, telling Apache which domain this configuration serves. Apache uses this to match incoming requests to the appropriate virtual host configuration.

ServerAlias allows additional hostnames to serve the same content. Common usage includes handling both www and non-www versions of a domain without separate configurations. Multiple aliases can be specified on separate lines or space-separated on one line.

The DocumentRoot directive defines the filesystem path where Apache looks for the website’s files. When a browser requests a page, Apache appends the URL path to the DocumentRoot to locate the requested file.

ErrorLog and CustomLog directives specify where Apache writes error and access logs respectively. Separate logs for each virtual host dramatically simplify troubleshooting when multiple sites share one server.

The <Directory> block controls access and behavior for specific filesystem directories. The Options directive enables features like directory indexes (showing file listings when no index.html exists) and following symbolic links. AllowOverride determines whether .htaccess files can override these settings, with None providing better performance by preventing per-directory configuration.

The Require all granted directive allows access from all clients. You can restrict access using Require ip followed by IP addresses or CIDR ranges for added security.

Verifying Apache Configuration Syntax

Configuration syntax errors prevent Apache from starting or cause unexpected behavior. Always test configurations before restarting the service:

sudo apachectl configtest

A successful test displays “Syntax OK”. Any errors include the file path and line number where problems were detected, simplifying corrections.

View how Apache interprets your virtual host configurations:

sudo httpd -S

This command lists all configured virtual hosts, their ServerNames, and the configuration files defining them. The output helps identify conflicts or missing configurations.

Common syntax errors include missing closing brackets, typos in directive names, or invalid file paths. The configuration test catches these issues before they cause service disruptions.

Restarting Apache Service

Apply configuration changes by restarting Apache:

sudo systemctl restart httpd

A full restart stops and starts the Apache service, loading all configuration changes. For minor configuration changes, reloading preserves existing connections while loading new configurations:

sudo systemctl reload httpd

Reloading is preferred in production environments where maintaining active connections matters. However, some changes require a complete restart to take effect.

Check for any startup errors:

sudo journalctl -u httpd -n 50

This displays the last 50 log entries for the httpd service, revealing any configuration problems or startup failures that might not be obvious from the systemctl status output.

Configuring DNS or Local Hosts File

Virtual hosts require proper domain name resolution to function. Production environments need DNS A records pointing your domains to the server’s IP address. Contact your domain registrar or DNS provider to configure these records, allowing propagation time of up to 48 hours.

For testing or development environments, modify the local hosts file instead:

sudo nano /etc/hosts

Add entries mapping your test domains to the appropriate IP address:

127.0.0.1 example1.com www.example1.com
127.0.0.1 example2.com www.example2.com

Use 127.0.0.1 for local testing or your server’s actual IP address when testing from other machines on your network. Save the file and exit the editor.

Test domain resolution:

ping example1.com

Successful resolution shows ping responses from the configured IP address. This confirms the hostname resolves correctly before testing the web server.

Testing Virtual Hosts

Open a web browser and navigate to your first virtual host:

http://example1.com

The test page you created earlier should display. Test the www variant as well:

http://www.example1.com

Both URLs should serve identical content due to the ServerAlias directive. Repeat the test for your second virtual host:

http://example2.com

Each virtual host should display its unique content, confirming Apache correctly routes requests based on the requested hostname.

Command-line testing using curl provides additional verification:

curl http://example1.com

This displays the HTML source without browser rendering, useful for automated testing or when GUI access isn’t available.

Check that log files are being created and written:

sudo ls -l /var/log/httpd/example1.com*.log

Each virtual host should generate separate access and error logs, confirming the configuration is fully operational.

Advanced Configuration Options

SSL/TLS certificates encrypt traffic between clients and your server, essential for production websites handling sensitive data. Let’s Encrypt provides free SSL certificates with automated renewal, making HTTPS accessible to everyone.

Redirect HTTP traffic to HTTPS by modifying your port 80 virtual host:

<VirtualHost *:80>
    ServerName example1.com
    ServerAlias www.example1.com
    Redirect permanent / https://example1.com/
</VirtualHost>

Configure custom error pages to maintain branding when errors occur:

ErrorDocument 404 /error-pages/404.html
ErrorDocument 500 /error-pages/500.html

Directory-specific access controls restrict sensitive areas:

<Directory "/var/www/example1.com/public_html/admin">
    AuthType Basic
    AuthName "Restricted Area"
    AuthUserFile /etc/httpd/.htpasswd
    Require valid-user
</Directory>

Enable compression to reduce bandwidth usage and improve load times:

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
</IfModule>

These advanced configurations enhance security, performance, and user experience beyond basic virtual host functionality.

Troubleshooting Common Issues

When virtual hosts display the default Apache page instead of expected content, verify the ServerName exactly matches the requested domain. Apache is case-sensitive and requires exact matches.

Permission denied errors typically indicate incorrect file ownership or permissions. Verify the apache user can read the DocumentRoot directory:

sudo namei -l /var/www/example1.com/public_html/index.html

This command displays permissions for every directory in the path, highlighting where access is blocked.

SELinux context issues on Fedora can prevent Apache from accessing files even with correct Unix permissions:

sudo restorecon -Rv /var/www/

This reapplies correct SELinux labels to your web directories.

If Apache fails to restart, the configuration test reveals specific syntax errors:

sudo apachectl configtest

Port conflicts occur when another service uses port 80 or 443. Check listening ports:

sudo ss -tlnp | grep ':80'

Firewall issues prevent external access even when local testing works. Verify rules allow web traffic and review firewalld’s configuration:

sudo firewall-cmd --list-all

Log files provide detailed information about request handling and errors:

sudo tail -f /var/log/httpd/example1.com-error.log

The -f flag follows the log in real-time, displaying new entries as they occur.

Security Best Practices

Keep your system updated with the latest security patches:

sudo dnf update

Regular updates address vulnerabilities in Apache and system packages. Configure automatic security updates for critical patches.

Disable directory listings in production environments unless specifically needed:

<Directory /var/www/example1.com/public_html>
    Options -Indexes
</Directory>

The minus sign removes the Indexes option, preventing attackers from browsing directory contents.

Configure proper SELinux contexts for custom directories:

sudo semanage fcontext -a -t httpd_sys_content_t "/var/www/example1.com(/.*)?"
sudo restorecon -Rv /var/www/example1.com

Implement HTTPS for all virtual hosts in production. Modern browsers flag HTTP sites as “Not Secure,” damaging user trust.

ModSecurity provides web application firewall functionality, blocking common attack patterns:

sudo dnf install mod_security

Regular log monitoring detects suspicious activity early. Tools like fail2ban automatically block IP addresses showing malicious behavior patterns.

Disable unnecessary Apache modules to reduce attack surface:

sudo dnf remove mod_autoindex mod_status

Store sensitive configuration files, database credentials, and private keys outside the DocumentRoot where they can’t be accidentally served to web visitors.

Performance Optimization Tips

Apache’s caching modules significantly improve response times for static content:

sudo dnf install mod_cache

Configure KeepAlive settings to reduce connection overhead:

KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

Tune Multi-Processing Module (MPM) settings based on your available memory and expected traffic:

<IfModule mpm_prefork_module>
    StartServers 5
    MinSpareServers 5
    MaxSpareServers 10
    MaxRequestWorkers 150
    MaxConnectionsPerChild 3000
</IfModule>

Enable compression for text-based content types:

LoadModule deflate_module modules/mod_deflate.so

Browser caching via mod_expires reduces repeated requests for static resources:

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
</IfModule>

Monitor server resources regularly using tools like htop, iotop, and Apache’s mod_status module. Performance tuning is an iterative process requiring monitoring and adjustment based on actual traffic patterns.

Congratulations! You have successfully installed VirtualHost Apache. Thanks for using this tutorial to configure virtual hosts Apache web server on Fedora 43 Linux system. For additional help or useful information, we recommend you check the official Apache 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