Sign In
Sign In

How To Secure Apache with Let's Encrypt on CentOS 9

How To Secure Apache with Let's Encrypt on CentOS 9
Shahid Ali
Technical writer
Apache
29.08.2024
Reading time: 5 min

Securing your Apache web server with SSL is essential for protecting data and ensuring user trust. Let's Encrypt provides a free and automated way to obtain and install SSL certificates. This guide will walk you through the steps to secure Apache with Let's Encrypt on CentOS 9.

In this tutorial, you will learn how to install and secure Apache with Let's Encrypt SSL certificates on a CentOS 9 server. This includes installing Apache, obtaining an SSL certificate from Let's Encrypt, configuring Apache to use the SSL certificate, and automating certificate renewal.

Prerequisites

Before you begin, ensure you have the following:

  • A CentOS 9 cloud server with a sudo non-root user.

  • A registered domain name pointing to your server's IP address.

Installing Apache on CentOS 9

First, update your package index and install Apache:

sudo dnf update
sudo dnf install httpd

Configuring Apache Virtual Host

To serve your website, you need to configure a virtual host for your domain.

1. Create a Directory for Your Website

Create a directory where your website files will be stored. For example, if your domain is example.com:   

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

2. Create a Test Page

Create a simple test page to ensure your virtual host is working:

echo '<html><head><title>Welcome to Example.com!</title></head><body><h1>Success! The Example.com server block is working!</h1></body></html>' > /var/www/example.com/html/index.html

3. Create the Virtual Host Configuration File

Create a configuration file for your virtual host:  

sudo vi /etc/httpd/conf.d/example.com.conf

Add the following configuration:    

<VirtualHost *:80>
ServerName example.com
ServerAlias www.example.com

DocumentRoot /var/www/example.com/html

<Directory /var/www/example.com/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>

ErrorLog /var/log/httpd/example.com_error.log
CustomLog /var/log/httpd/example.com_access.log combined
</VirtualHost>

Replace example.com with your actual domain name.

4. Test the Configuration 

Run the following command to check for syntax errors:

sudo apachectl configtest

If the output is `Syntax OK`, you can proceed.

5. Restart Apache

Restart Apache to apply the new configuration:

sudo systemctl start httpd

Now check the status of the httpd service:

sudo systemctl status httpd

Image1

Now, you can access your website by typing your domain name in the web browser (e.g., http://example.com). If you see the test page, your Apache server is configured correctly.

Enable Apache to start on boot:

sudo systemctl enable httpd

Installing Certbot

Certbot is a straightforward tool that simplifies the process of obtaining a certificate from Let's Encrypt and installing it on your web server. To get started with Certbot, you first need to activate the EPEL repository. After that, you can install the Certbot Apache plugin by running these commands:

sudo dnf install epel-release

Install Certbot and the Apache plugin:

sudo dnf install certbot python3-certbot-apache

Obtaining an SSL Certificate

Once Certbot is set up, you can proceed to request an SSL certificate for your domain. Execute the following command and follow the interactive prompts:

sudo certbot --apache -d your_domain -d www.your_domain

Throughout the process, you'll be asked to enter an email address for notifications and to accept the terms of service. Additionally, you'll have the option to redirect HTTP traffic to HTTPS, which is recommended for enhanced security.

Verifying HTTPS Configuration

Once the certificate is issued, Certbot will automatically adjust your Apache configuration. To confirm these changes, reload Apache with the following command:

sudo systemctl restart httpd

Next, open your web browser and visit your domain with https://. You should see a lock icon, signifying that your site is now secure.

Automating Certificate Renewal

Let's Encrypt certificates are valid for 90 days. To automate the renewal process, create a cron job:

sudo crontab -e

Add the following line to renew the certificate automatically:

0 0 * * * /usr/bin/certbot renew --quiet

This cron job will run daily at midnight, and Certbot will renew the certificate if it is within 30 days of expiration.

Configuring Apache to Use Let's Encrypt SSL

Certbot automatically configures Apache to use the obtained SSL certificate. However, you can manually adjust the configuration if needed. Open the Apache SSL configuration file:

sudo vi /etc/httpd/conf.d/ssl.conf

Ensure the following lines are present and correctly configured:

SSLCertificateFile /etc/letsencrypt/live/your_domain/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/your_domain/privkey.pem
SSLCertificateChainFile /etc/letsencrypt/live/your_domain/chain.pem

Restart Apache to apply the changes:

sudo systemctl restart httpd

Testing SSL Configuration

Test your SSL configuration using an online tool like SSL Labs' SSL Test. Enter your domain to ensure everything is set up correctly.

Troubleshooting Common Issues

Issue: Certbot Command Not Found

If you encounter a "command not found" error when running Certbot, ensure it is installed correctly and try reinstalling:

sudo dnf install certbot python3-certbot-apache

Issue: Apache Not Restarting

If Apache fails to restart after configuring SSL, check the configuration files for syntax errors:

sudo apachectl configtest

Fix any errors and try restarting Apache again:

sudo systemctl restart httpd

Conclusion

Securing Apache with Let's Encrypt SSL on CentOS 9 enhances the security of your web server and ensures the integrity of data transmitted between your server and clients. By following this guide, you have successfully installed Apache, obtained and configured an SSL certificate, and automated the renewal process.

Apache
29.08.2024
Reading time: 5 min

Similar

Apache

How to Install Let’s Encrypt with Apache

In the current environment of the internet, the use of HTTPS to secure web traffic is a must. With a free and automated Certificate Authority (CA) service like Let’s Encrypt, adoption of SSL/TLS has changed dramatically because you can quickly obtain trusted certificates at no cost. This guide will walk you through installing a Let’s Encrypt certificate on an Apache web server running Ubuntu 22.04 (Jammy Jellyfish). You will configure Certbot (the official Let’s Encrypt client), set up renewal procedures, and establish good security practices. Prerequisites Before proceeding, ensure you have: An Ubuntu 22.04 system. Update it with: sudo apt updatesudo apt upgrade Apache Installed: Confirm with apache2 -v. If not present, install via: sudo apt updatesudo apt install apache2 A registered domain (e.g., example.com) pointing to your server’s public IP. Check with: ping example.com Firewall Configured: Allow HTTP/HTTPS traffic: sudo ufw allow 'Apache Full'sudo ufw enable   Sudo Privileges: Access to a user account with administrative rights. Step 1: Installing Certbot via Snap Let’s Encrypt recommends using Certbot through Snap for seamless updates. Ubuntu 22.04 includes Snap by default, but make sure it’s updated: sudo snap install coresudo snap refresh core Install Certbot: sudo snap install --classic certbot Create a symbolic link to the Certbot binary for easy access: sudo ln -s /snap/bin/certbot /usr/bin/certbot Step 2: Generating SSL Certificate with Certbot Certbot integrates with Apache to automate certificate issuance and configuration. Run: sudo certbot --apache Follow the interactive prompts: Email Address: Enter for urgent renewal notifications. Terms of Service: Accept by typing A. Domain Selection: Choose the domain(s) to secure (e.g., example.com, www.example.com). HTTP to HTTPS Redirect: Select 2 to enforce HTTPS universally. Certbot will: Generate certificates in /etc/letsencrypt/live/exple.com/. Modify virtual host files to activate SSL. Reload Apache to apply changes. Step 3: Verifying Apache Configuration Certbot updates automatically your configuration. Inspect the virtual host file for your domain: sudo nano /etc/apache2/sites-available/example.com-le-ssl.conf Look for directives like: SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pemSSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pemInclude /etc/letsencrypt/options-ssl-apache.conf Ensure the SSL module is enabled: sudo a2enmod sslsudo systemctl restart apache2 Step 4: Testing SSL/TLS Configuration Validate your setup: Visit https://example.com. Look for the padlock icon. Use curl to check headers: sudo apt install curlcurl -I https://example.com Confirm HTTP/2 200 or HTTP/1.1 200 OK. Run a free analysis at SSL Server Test to discover vulnerabilities. Step 5: Automating Renewal Let’s Encrypt certificates expire every 90 days. Certbot automates renewal via a systemd timer. Test renewal manually: sudo certbot renew --dry-run If successful, Certbot’s timer will handle future renewals. Verify the timer status: systemctl list-timers | grep certbot Troubleshooting Common Issues Port Blocking: Ensure ports 80 and 443 are open: sudo ufw status Incorrect Domain Resolution: Verify DNS records with: dig example.com Configuration Errors: Check logs via: sudo journalctl -u apache2 Certificate Renewal Failures: Inspect Certbot logs at /var/log/letsencrypt/. Advanced Configurations Enforcing HTTPS with HSTS Add the Strict-Transport-Security header to your SSL config: sudo a2enmod headerssudo systemctl restart apache2 Then in the Apache config (/etc/apache2/apache2.conf) configure: Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" Redirecting HTTP to HTTPS Certbot usually handles this, but manually update non-SSL virtual hosts: <VirtualHost *:80> # Define the primary domain name for this virtual host ServerName example.com # Redirect all HTTP traffic to HTTPS permanently (status code 301) # This ensures users always access the site securely Redirect permanent / https://example.com/ </VirtualHost> Optimizing Cipher Suites Edit /etc/letsencrypt/options-ssl-apache.conf to prioritize strong ciphers: SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDHSSLProtocol All -SSLv2 -SSLv3 -TLSv1 -TLSv1.1 To further enhance your Apache and Let’s Encrypt setup, consider implementing the following advanced optimizations. These steps will not only improve security but also ensure your server performs efficiently under high traffic and adheres to modern web standards. Implementing OCSP Stapling Online Certificate Status Protocol (OCSP) stapling improves SSL/TLS performance by allowing the server to provide proof of validity, reducing client-side verification delays. Enable OCSP stapling in your configuration (/etc/apache2/apache.conf): SSLUseStapling onSSLStaplingCache "shmcb:logs/stapling-cache(150000)" After making these changes, restart the web server: sudo systemctl restart apache2 Verify OCSP stapling is working: openssl s_client -connect example.com:443 -status -servername example.com Look for OCSP Response Status: successful in the output. Configuring HTTP/2 for Improved Performance HTTP/2 enhances web performance by enabling multiplexing, header compression, and server push. To enable HTTP/2 in Apache, first ensure the http2 module is enabled: sudo a2enmod http2 Then, add the following directive to your SSL virtual host: Protocols h2 http/1.1 Restart Apache to apply the changes: sudo systemctl restart apache2 Verify HTTP/2 is active by inspecting the response headers using browser developer tools or a tool like curl: curl -I -k --http2 https://example.com Setting Up Wildcard Certificates If you manage multiple subdomains, a wildcard certificate simplifies management. To obtain a wildcard certificate with Certbot, use the DNS challenge method. First, install the DNS plugin for your DNS provider (e.g., Cloudflare): sudo snap set certbot trust-plugin-with-root=ok sudo snap install certbot-dns-cloudflare Install pip and the cloudflare package: sudo apt updatesudo apt install python3-pipsudo pip install cloudflare Create a credentials file for your DNS provider: sudo nano /etc/letsencrypt/cloudflare.ini Add your API credentials: dns_cloudflare_api_token = your_api_key Secure the file: sudo chmod 600 /etc/letsencrypt/cloudflare.ini Request the wildcard certificate: sudo certbot certonly --dns-cloudflare --dns-cloudflare-credentials /etc/letsencrypt/cloudflare.ini -d example.com -d *.example.com Update your configuration to use the wildcard certificate. Monitoring and Logging SSL/TLS Usage Regularly monitoring SSL/TLS usage helps identify potential issues and enhance performance. Apache’s mod_ssl module provides detailed logs. Enable logging by integrating the following to your SSL virtual host configuration: LogLevel info ssl:warnCustomLog ${APACHE_LOG_DIR}/ssl_access.log combinedErrorLog ${APACHE_LOG_DIR}/ssl_error.log Analyze logs for errors or unusual activity: sudo tail -f /var/log/apache2/ssl_error.log For advanced monitoring, consider tools like GoAccess or ELK Stack to visualize traffic patterns and SSL/TLS performance. Enhancing Security with Security Headers Adding security headers to your configuration can protect your site from common vulnerabilities like cross-site scripting (XSS) and clickjacking. Include the following directives in your virtual host file: Header set X-Content-Type-Options "nosniff"Header set X-Frame-Options "DENY"Header set X-XSS-Protection "1; mode=block"Header set Content-Security-Policy "default-src 'self';" These headers make sure that browsers enforce strict security policies, minimizing the risk of attacks. Final Thoughts Securing your Apache as of Ubuntu 22.04 using Let's Encrypt is a must-do to create a trusted quality web presence. In this tutorial, we have learned how to fine-tune some of the advanced configuration options, such as OCSP stapling, HTTP/2, wildcard certificates, as well as monitoring and security headers. These configurations will help you protect your server while increasing its efficiency and scalability. Note that web security is an ongoing process! Stay informed about new and developing threats, updated SSL/TLS standards, and audit your setup and logs regularly to maintain your server security after securing it.
27 March 2025 · 7 min to read
Apache

How To Install the Apache Web Server on Ubuntu 22.04

Apache stands out as one of the most recognized and broadly utilized open-source web platforms across the globe. It is renowned for its dependability, adaptability, and profound usage. Its modular design, rich feature set, and compatibility with diverse operating systems make it a preferred choice for developers and IT professionals. For both novice and seasoned administrators, knowing how to do the installation and configuration of Apache properly is crucial, whether they are managing a sophisticated online infrastructure or setting up a simple website. With the help of this tutorial, users will build a reliable foundation for their web hosting requirements by installing Apache on Ubuntu 22.04, setting it up for maximum performance, and confirming that it is operating successfully. By employing the outlined procedures, administrators can guarantee a secure, scalable, and efficient environment, ready to support diverse online platform applications and services. Prerequisites Make sure the following requirements are satisfied before starting the installation of the Apache web server on Ubuntu 22.04 to lower the possibility of mistakes and guarantee a flawless setup. Ubuntu 22.04 System: Make sure Ubuntu 22.04 is installed on the cloud server or virtual machine. Access Rights: User must have root or sudo access to the platform. Online Connection: In order to download and install Apache and related software, a steady web connection is necessary. Domain Name (optional): Having a registered domain name is advised for anyone wishing to deploy a website. Before configuring the Apache web server, the DNS settings should be set up to point the domain to the server's IP address. System Update Ensure the engine is fully updated prior to starting the installation process. System updates reduce compatibility problems during installation by verifying that every software packages, libraries, and dependencies are up to date. Log in with administrative credentials to the server. Execute the following command for updating the system's package index. sudo apt update This will retrieve the most recent data on software and package versions from the repositories. Subsequently, upgrade the installed packages to the most recent versions by deploying the instruction below:  sudo apt upgrade Apache Installation Ubuntu's default repositories contain Apache. Employ the following command to install the core Apache package and its dependencies.  sudo apt install apache2 -y Once the installation is finished, validate if Apache was successfully installed by looking up its version. apache2 -v Next, verify that Apache is operational. sudo systemctl status apache2 Permit Apache Traffic Through the Firewall Apache traffic must be permitted if your server has the Uncomplicated Firewall (UFW) enabled. Add the necessary rules. First, make sure SSH connections are allowed: sudo ufw allow ssh Then, add the specific rule for Apache: sudo ufw allow 'Apache Full' To verify that the Apache traffic is allowed, check the status of the UFW rules. sudo ufw status Test Apache Installation Launch an internet browser and navigate to your server's IP address to make sure Apache is operating. The default Apache "Welcome Page" will be displayed if Apache is installed correctly. http://server-ip You can find the server's IP address on the server Dashboard in your Hostman control panel. You can also determine the IP address for the server by employing the command below. Check the inet field for the IP address. ip addr show In this case, the IP address of the server is 166.1.227.224. So we visit it in the web browser: http:// 166.1.227.224 Control the Apache Service To manage the Apache service, use these fundamental commands: sudo systemctl start apache2  – employ this to initialise Apache engine. sudo systemctl stop apache2  – employ this command to halt the Apache. sudo systemctl restart apache2  – employ this to reinitialise the Apache engine. sudo systemctl enable apache2  – to configure the Apache engine to start automatically upon reboot. sudo systemctl disable apache2  – to prevent the Apache service from launching automatically after a system reboot. Set up Apache (Optional) The Apache configuration files are located in /etc/apache2/. Typical configuration tasks include the techniques mentioned below. sudo nano /etc/apache2/apache2.conf This will open the main configuration file for modifying. This file manages a variety of server settings, including Apache's behavior, security protocols, and how it processes incoming web requests. /etc/apache2/sites-available This is a directory that houses virtual host configuration files in the Apache web server's configuration hierarchy. By setting distinct domains or subdomains, virtual hosts enable users to operate several websites or apps on a single Apache server. Virtual hosts allow administrators to employ several websites or web applications on a single Apache server, making it an effective solution for minimising infrastructure expenses and simplifying server management. This capability streamlines operations by consolidating multiple sites onto one server, reducing the need for additional hardware and enhancing resource utilisation. sudo a2ensite apache-config.conf This method is utilised to activate a site-specific Apache web server configuration file on systems located on /etc/apache2/sites-available/. Whenever this command is executed, the file /etc/apache2/sites-available/apache-config.conf is linked to /etc/apache2/sites-enabled/. sudo a2dissite apache-config.conf This method is used to disable a site-specific Apache web server configuration file on systems located on /etc/apache2/sites-available/. Whenever this command is executed, the file /etc/apache2/sites-available/apache-config.conf is unlinked to /etc/apache2/sites-enabled/. sudo apache2ctl configtest The goal is to verify the syntax of the configuration files for the Apache web server prior to making any modifications or restarting the service. It makes sure that the configuration files don't contain any invalid directives or syntax mistakes that could cause Apache to crash on a restart or reload. sudo systemctl reload apache2 This is used to refresh the settings of the Apache web server without halting or disrupting ongoing connections whenever there is change made on the apache configuration. Secure Apache with SSL (Optional) Installing Certbot and the Apache plugin with the command below is the standard way to secure the Apache server with HTTPS. sudo apt install certbot python3-certbot-apache -y Use Certbot to set up SSL automatically by employing the command below. Set up the SSL certificate by following the instructions on prompt (see highlighted in yellow). sudo certbot --apache Conclusion One essential step in hosting web apps or providing webpages on Ubuntu 22.04 is installing and configuring the Apache web server. Administrators can create a dependable and expandable web server environment by following the described procedures, which include installing and maintaining virtual hosts as well as testing settings. By ensuring the integrity of configuration files, operations such as sudo apache2ctl configtest lower the possibility of errors or outages. Because of its adaptability, stability, and broad community support, Apache remains a fundamental component of web hosting solutions, making it a necessary competency for both developers and IT professionals.
14 January 2025 · 6 min to read
Apache

How to Install Apache on CentOS

The Apache web server is the most widely used platform for deploying HTTP-based services. Its popularity is due to its support for dynamically loadable modules, compatibility with various file formats, and integration with other software tools. Prerequisites To install the Apache HTTP server following this guide, you will need: A local computer or a cloud server with CentOS 9 installed A user with sudo privileges or root Enabled firewalld Step 1: Install Apache The Apache package is available in the official CentOS repository, so you can install it using dnf. First, update the package list: sudo dnf update -y Run the following command to install Apache: sudo dnf install httpd -y The package manager will install the Apache web server and all necessary dependencies on CentOS. Step 2: Configuring the Firewall To operate the web server, you’ll need to configure the firewall to allow HTTP and HTTPS traffic: sudo firewall-cmd --permanent --add-service=httpsudo firewall-cmd --permanent --add-service=https After running these commands, restart the firewall to apply the new rules: sudo firewall-cmd --reload The Apache installation is now complete, and you can start the web server and check its functionality. Step 3: Checking the HTTP Server Once installed, Apache isn’t running yet, so you need to enable and start it using these commands: sudo systemctl enable httpdsudo systemctl start httpd To verify if the Apache service has started, use this command: sudo systemctl status httpd If the web server is running correctly, you should see a message showing the status as active (running): ● httpd.service - The Apache HTTP Server     Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; preset: disabled)     Active: active (running) since Thu 2024-11-07 07:34:27 GMT; 6s ago Another way to check is to open the server’s IP address in a browser: http://your_server_ip You can find your server’s IP on the server's Dashboard or in an email received after setting up the server. Step 4: Managing the Apache Service Now, you can try some systemctl commands for interacting with the Apache service.  For example, to stop the HTTP server, use: sudo systemctl stop httpd To start it again, use: sudo systemctl start httpd For a complete restart, such as when applying configuration changes: sudo systemctl restart httpd To reload Apache without interrupting active connections, use: sudo systemctl reload httpd We enabled Apache to start automatically when the server boots. If you prefer to disable this option, run: sudo systemctl disable httpd These commands allow you to manage the Apache process easily. Step 5: Setting Up Virtual Hosts The default Apache HTTP server configuration allows for hosting only one site. However, you can set up virtual hosts to host multiple sites with separate resources. Virtual hosts in Apache work similarly to those in Nginx. They allow you to separate configurations and host multiple domains on a single virtual or physical server. In this guide, we’ll use a placeholder site called example.com. When configuring, replace it with your actual domain. Create the html directory for example.com: sudo mkdir -p /var/www/example.com/html Create a directory for log files: sudo mkdir -p /var/www/example.com/log Set permissions for the html directory. Assign ownership to the $USER environment variable. sudo chown -R $USER:$USER /var/www/example.com/html Verify standard permissions for the root directory: sudo chmod -R 755 /var/www Create an index.html file. You can use any code editor to create this file. For example, with vi: sudo vi /var/www/example.com/html/index.html Add simple content to the file: <html> <head> <title>Welcome to Example.com!</title> </head> <body> <h1>Success! The example.com virtual host is working!</h1> </body> </html> After saving index.html, you’re nearly ready to set up the configuration files for each domain. These files will tell Apache how to handle requests for each virtual host. Create directories for virtual host configurations. The configuration files for individual domains are stored in a sites-available directory, while the sites-enabled directory will contain symbolic links to sites that are ready to receive traffic: sudo mkdir /etc/httpd/sites-available /etc/httpd/sites-enabled Now, you need to instruct the HTTP server to find virtual hosts in the sites-enabled directory. To do this, modify the main Apache configuration file by running the following command: sudo vi /etc/httpd/conf/httpd.conf Then, move the cursor to the very end of the file and add the following lines: # Supplemental configuration # # Load config files in the "/etc/httpd/conf.d" directory, if any. IncludeOptional conf.d/*.conf IncludeOptional sites-enabled/*.conf Now, it’s time to create the virtual host configuration file: sudo vi /etc/httpd/sites-available/example.com.conf In this file, add the following configuration: <VirtualHost *:80> ServerName www.example.com ServerAlias example.com DocumentRoot /var/www/example.com/html ErrorLog /var/www/example.com/log/error.log CustomLog /var/www/example.com/log/requests.log combined </VirtualHost> Make sure to replace example.com with your actual domain name. This configuration tells the web server where to find the site’s root directory and where to store the error and access logs. After saving and closing the file, you need to activate the virtual host by creating a symbolic link for the domain in the sites-enabled directory: sudo ln -s /etc/httpd/sites-available/example.com.conf /etc/httpd/sites-enabled/example.com.conf At this point, the configuration is complete, and the host is ready to function. However, before restarting the web server, it’s a good idea to check if the SELinux module is correctly handling requests. Step 6: Configuring Permissions in SELinux The SELinux (Security-Enhanced Linux) module enhances the operating system's security. CentOS comes with a preconfigured SELinux package that works with Apache. However, since we've made changes, starting the web server services might result in an error. To resolve this, you need to adjust SELinux policies for Apache. There are two ways to adjust these policies: a universal approach and a folder-specific approach. Option 1: Universal Approach This method allows the SELinux security module to use any Apache processes via the httpd_unified boolean variable. It’s convenient but doesn’t allow separate policies for individual directories and files. To enable the universal policy, run: sudo setsebool -P httpd_unified 1 The setsebool command is used to modify boolean values, and the -P flag ensures that the change is persistent across reboots. In this case, the httpd_unified boolean is activated with the value 1. Option 2: Adjusting SELinux Policies for Specific Directories This approach requires more steps but allows for more granular control over permissions for each directory or file. You’ll need to specify the context type for each new folder manually. For example, to check the parameters of the /var/www/example.com/log directory, run: sudo ls -dlZ /var/www/example.com/log/ You’ll see something like this: drwxr-xr-x. 2 root root unconfined_u:object_r:httpd_sys_content_t:s0 6 Nov 07 09:01 /var/www/example.com/log/ You can see that the context used is httpd_sys_content_t, meaning Apache can only read files placed in this folder. To change the context to httpd_log_t so that the web server can write to log files, run: sudo semanage fcontext -a -t httpd_log_t "/var/www/example.com/log(/.*)?" This command will set the correct context for the log directory and its contents, allowing Apache to write log entries. Apply the changes using the following command: sudo restorecon -R -v /var/www/example.com/log The -R flag allows the command to run recursively, updating existing files, and the -v flag will display the changes being made. You should see an output like this: Relabeled /var/www/example.com/log from unconfined_u:object_r:httpd_sys_content_t:s0 to unconfined_u:object_r:httpd_log_t:s0 If you want to verify that the context type has been updated, check the current status again: sudo ls -dlZ /var/www/example.com/log/ The output should look like this: drwxr-xr-x. 2 root root unconfined_u:object_r:httpd_log_t:s0 6 Nov 07 09:01 /var/www/example.com/log/ Step 7: Testing the Virtual Host After adjusting the SELinux permissions, the Apache server should now be able to write data to the /var/www/example.com/log directory. Let’s restart the Apache service: sudo systemctl restart httpd Next, list the contents of the /var/www/example.com/log directory to verify that the system has created the log files: ls -lZ /var/www/example.com/log You should see output similar to this: -rw-r--r--. 1 root root system_u:object_r:httpd_log_t:s0 0 Nov 07 09:06 error.log-rw-r--r--. 1 root root system_u:object_r:httpd_log_t:s0 0 Nov 07 09:06 requests.log The first line confirms the existence of the error.log file, and the second confirms the presence of the requests.log file. Now, you can check the functionality of the domain through a browser. You should see a message like: Success! The example.com virtual host is working This confirms that the virtual host has been successfully set up and is serving content. Repeat steps 5 and 6 for each new site, replacing the domain with the appropriate one. Conclusion In this tutorial, we've walked through installing and configuring Apache on CentOS 9, including setting up virtual hosts for multiple domains. We covered installation with dnf, configuring firewall rules, enabling Apache to start on boot, and managing its service using systemctl. We also explored SELinux configuration for proper permissions, ensuring Apache can read and write log files. With these steps, you'll have a functional web server ready to host sites and deploy content.
11 November 2024 · 8 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support