Apache HTTP Server (httpd) is one of the most popular and robust web servers available, known for its flexibility, performance, and wide range of features. It is widely used for hosting websites and web applications. Setting up Apache on CentOS Stream 9 allows you to leverage its powerful capabilities for your web hosting needs. Additionally, securing your website with a free SSL certificate from Let’s Encrypt ensures that your site is encrypted and trustworthy.
To install Apache HTTP Server on CentOS Stream 9 and set up a Let’s Encrypt SSL certificate, follow the steps outlined in this guide. This will provide you with a secure and efficient web server configuration.
Ensuring a Fully Updated CentOS Stream System Before Apache Installation
Before proceeding with the Apache installation on your CentOS Stream machine, we must verify that our system is fully up-to-date. This is more than just a precautionary measure. Updating your system helps prevent compatibility issues and significantly enhances its stability, security, and performance.
To put this into motion, execute the following command in your terminal:
sudo dnf upgrade --refresh
This command sets off the update mechanism, procuring and installing your system’s latest software updates and security patches. It is crucial to allow the update process to fully conclude before advancing to the Apache installation. This ensures that your system is in its prime condition, optimally configured, and prepped to run Apache without encountering any snags or compatibility issues.
Install Apache HTTPD via DNF Command
The second step is to install Apache, or HTTPD, on your CentOS Stream system. This is a straightforward process, courtesy of the powerful DNF package manager. The DNF, or Dandified Yum, package manager simplifies installing, updating, and managing software packages.
Kickstart the installation of Apache (HTTPD) by running the following command in your terminal:
sudo dnf install httpd
This command initiates the installation mechanism and fetches and installs all the necessary components to allow Apache (HTTPD) to run on your system. The process should finish in just a few minutes. Afterward, you will have Apache (HTTPD) fully installed and ready for use.
Activating and Configuring Apache HTTPD to Run on System Boot
Following the successful installation of Apache (HTTPD) on your CentOS Stream system, the following key action is to activate the service and configure it to launch automatically upon system boot. Apache (HTTPD) is always active and prepared to serve web requests when your system powers up.
If the Apache (HTTPD) service is not active or set to run by default, use these commands in your terminal to start the service and ensure it runs on system boot:
sudo systemctl start httpd
sudo systemctl enable httpd
The first command, sudo systemctl start httpd, fires up the Apache (HTTPD) service, whereas the second command, sudo systemctl enable httpd, sets the service to run automatically upon system boot. By implementing these two commands, you guarantee that Apache (HTTPD) is constantly accessible and active, ready to cater to web requests each time your system turns on.
As an alternative, you can condense the two previous steps into one single command:
sudo systemctl enable httpd --now
The –now option in the command sudo systemctl enable httpd –now simultaneously starts the Apache (HTTPD) service and configures it to launch on the system boot automatically. This single command unifies the two separate commands from the previous steps, making the process more streamlined and efficient.
Check Apache HTTPD Service Status
Finally, we should verify the successful implementation and functioning of Apache (HTTPD) by utilizing the following systemctl command:
systemctl status httpd
This command provides you with the real-time status of the Apache (HTTPD) service, including any errors or messages that may have arisen. By scrutinizing the status of the service, you can confirm that Apache (HTTPD) is running seamlessly.
Configure FirewallD Rules
After installing Apache (HTTPD) on CentOS Stream, you might notice that the firewall doesn’t include preconfigured rules for standard ports 80 and 443. You must configure these firewall rules before moving forward to improve the security of your web application.
Set the firewall rules using the firewall-cmd tool, CentOS Stream’s default firewall management utility. The rules you need to configure will vary depending on the ports you intend to use. However, we list all critical options in the following steps.
Opening Ports 80 and 443
We will run the first two commands to open ports 80 and 443. These ports handle incoming HTTP and HTTPS traffic, respectively.
To open port 80 or HTTP, run the following command:
sudo firewall-cmd --permanent --add-port=80/tcp
Next, open port 443, or HTTPS, with the subsequent command:
sudo firewall-cmd --permanent --add-port=443/tcp
Verify Firewall Changes
After specifying the ports to open, we must instruct the firewall to implement these changes. Do this by reloading the firewall rules using the command below:
sudo firewall-cmd --reload
Understanding the Implications
It is paramount to have a keen understanding of the security implications accompanying opening ports on your system. By selectively opening only the necessary ports, you bolster your web application’s defense against unauthorized access and potential security threats. This underlines why it is critical to properly configure the firewall rules for your Apache (HTTPD) installation on CentOS Stream.
Verifying Apache HTTPD Access
After meticulously configuring Firewalld, ensure you can access the Apache (HTTPD) landing page through your web browser. Launch your favorite web browser and go to either http://localhost or http://your_server_ip.
To access via your server’s IP:
http://your_server_ip
Alternatively, to access via localhost:
http://localhost
When you configure everything precisely, the Apache (HTTPD) default landing page will greet you. This page displays a message confirming that the server operates as expected. The page will resemble:
Create and Configure a Virtual Host
This section will delve into the practical aspect of creating a virtual host using Apache (HTTPD), a flexible web server known for its capability to host multiple domains on a single server. This utility is analogous to the “server blocks” attribute of Nginx. In the ensuing tutorial, we’ll illustrate how to formulate a virtual host for a given domain, represented as “example-domain.com.” Naturally, you’ll substitute this sample domain with your specific domain name.
Creating virtual hosts facilitates independent management of configurations for each domain. This provides control over various facets of your web server environment, including security, performance, and custom settings. This can prove particularly advantageous if you aim to host multiple websites on a single server or maintain separate settings for distinct sections of your website. With Apache (HTTPD), you can effortlessly devise virtual hosts to meet these requirements.
Creating and Configuring Directories
Commencing your virtual host setup involves creating a new directory that serves as the root folder for your virtual host. The name of this directory typically aligns with your domain name.
For instance, if your domain name is “example.com,” you would generate a new directory with the command:
sudo mkdir /var/www/example.com
This command necessitates the replacement of “example.com” with your domain name. Thus, The directory will house files and assets associated with your virtual hosts, including HTML files, images, scripts, and other resources.
Setting up individual directories for each virtual host facilitates a distinct separation of concerns, which is significant in the context of security and troubleshooting.
The new directory may require appropriate ownership and permissions to allow Apache (HTTPD) access. The succeeding commands set the correct ownership and permissions:
sudo chown -R apache:apache /var/www/example.com
sudo chmod -R 755 /var/www/example.com
With the new directory primed, we can set up your virtual host.
Creating an index.html File
A text editor generates an index.html file for your virtual host. For our tutorial, we’ll use the nano text editor, though you can choose any text editor you prefer.
Execute the following command to create the index.html file:
sudo nano /var/www/example.com/index.html
In the text editor, commence creating the content for your index.html file. This file typically serves as the first point of contact for a user visiting your website.
Here’s a simple example:
<html>
<head>
<title>Example Domain</title>
</head>
<body>
<h1>Welcome to Example Domain</h1>
<p>This is a sample page for the domain example.com.</p>
</body>
</html>
Upon finalizing the content of your index.html file, save the file and exit the text editor. In the case of nano, this is accomplished by pressing Ctrl + X, Y, and Enter.
Configuring Virtual Host Directories
Ensuring proper directory setup for the Apache web server guarantees a seamless and organized configuration. Specifically, the “sites-available” and “sites-enabled” directories are used. This configuration mirrors the one adopted in Nginx and promotes organized and accessible configurations.
To create these directories, use the following command:
sudo mkdir /etc/httpd/sites-available /etc/httpd/sites-enabled
Subsequently, instruct Apache to look for virtual host files in the “/etc/httpd/sites-available” directory:
sudo nano /etc/httpd/conf/httpd.conf
In the opened configuration file, append the line “IncludeOptional sites-enabled/*.conf” at the end. This line instructs Apache to include all virtual host configuration files in the “sites-enabled” directory.
IncludeOptional sites-enabled/*.conf
Optionally, you might want to comment “IncludeOptional conf.d/*.conf”, disabling the default folder where Apache searches for virtual host files. This helps in preventing any potential confusion.
Example:
#IncludeOptional conf.d/*.conf
IncludeOptional sites-enabled/*.conf
To save the file and exit, use the keyboard combination CTRL + O, followed by CTRL + X.
Create the Virtual Host Configuration File
Next, using your text editor, we will create a virtual host configuration file at /etc/httpd/sites-available/example.com.conf.
sudo nano /etc/httpd/sites-available/example.com.conf
Fill in the placeholder information in the following configuration block with your ServerName, ServerAlias, and Document Root before copying it into the virtual host configuration file located at /etc/httpd/sites-available/example.com.conf.
<VirtualHost *:80>
ServerAdmin webmaster@localhost
ServerName example_domain
ServerAlias www.example_domain
DocumentRoot /var/www/example.com/
</VirtualHost>
Adjust the server directives to fit your specific requirements.
Step 5: Modifying Access Permissions
To grant public access to your server, modify the access permissions for the Apache service in the /etc/httpd/conf/httpd.conf configuration file. The default configuration denies access. If you neglect this step, you might encounter HTTP 403 errors when people try to access your website.
sudo nano /etc/httpd/conf/httpd.conf
Add the following block to your file, ensuring that you adjust the root directory to match your own.
<Directory /var/www/example.com/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
To save these changes, use the keyboard combination of CTRL+O and exit the text editor using CTRL+X.
Step 6: Enable the Virtual Host for Apache on CentOS Stream
To set up the virtual host, you must activate it as the final step. Create a symbolic link from the sites-available directory to the sites-enabled directory using the command provided below:
sudo ln -s /etc/httpd/sites-available/example.com.conf /etc/httpd/sites-enabled/
You need to restart the Apache service to complete the activation process.
sudo systemctl restart httpd
After restarting the Apache service, open your web browser and navigate to “HTTP://example_domain.” If you haven’t registered a domain, you can access your website using the IP address (local or remote). If you set everything up correctly, the landing page you created in the index.html file will greet you.
Additional Commands & Tips
Secure Directories and Files
Setting Secure Permissions
Using secure permissions for files and directories in Apache on CentOS is crucial. Often, excessive permissions are granted, like full public access. To prevent security risks, it’s recommended to limit permissions. For directories, use chmod 755
and for files, chmod 644
. Below are the commands for setting these permissions. Remember, some applications may require different permissions, like 777
for phpBB.
- For directories:
sudo find /var/www/example.com/ -type d -exec chmod 755 "{}" \;
- For files:
sudo find /var/www/example.com/ -type f -exec chmod 644 "{}" \;
These commands will replace /var/www/example.com/
with the appropriate directory path. This step doesn’t guarantee complete security but significantly reduces risks by preventing public access to crucial files.
Secure Apache with Let’s Encrypt SSL
Installing Let’s Encrypt SSL Certificate
Securing your Apache server with an SSL certificate is necessary for safe client-server connections. Let’s Encrypt provides a free, automated SSL certificate. First, ensure the CRB repository is enabled, and the EPEL repository is installed. The installation process varies slightly between CentOS Stream 9 and 8.
For CentOS Stream 9:
- Enable CRB:
sudo dnf config-manager --set-enabled crb
- Install EPEL repository:
sudo dnf install https://dl.fedoraproject.org/pub/epel/epel-release-latest-9.noarch.rpm
Next, install mod_ssl
and Snap:
sudo dnf install mod_ssl
Activate EPEL on your CentOS Stream distribution, and then install Snap.
sudo dnf install snapd -y
After installation, make sure to enable Snap and on system startup immediately.
sudo systemctl enable snapd --now
The next step is to install the snap core, which will take care of all the dependencies needed for snap packages to run.
sudo snap install core
Create a symbolic link for the snapd directory.
sudo ln -s /var/lib/snapd/snap /snap
Use the following terminal command to install the Certbot snap package.
sudo snap install --classic certbot
Finally, create another symbolic link for the Certbot snap package.
sudo ln -s /snap/bin/certbot /usr/bin/certbot
Run Certbot for Apache
Run the following command in your terminal to generate your SSL certificate using Certbot.
sudo certbot --dry-run --apache --agree-tos --redirect --hsts --staple-ocsp --email you@example.com -d www.example.com
For those new to Let’s Encrypt, you may seek more information on the abbreviation in the command.
- The “–dry-run” option lets you execute a test run of the certificate generation process without altering the system. This option is valuable for testing.
- The “–apache” option is to generate a certificate for an Apache web server.
- The “–agree-tos” option allows you to accept the terms of service from Let’s Encrypt, the certificate authority that provides the SSL certificate.
- The “–redirect” option automatically redirects all HTTP traffic to HTTPS.
- The “–hsts” option enables HTTP Strict Transport Security (HSTS). This security feature helps protect against protocol downgrade attacks and cookie hijacking by telling browsers only to access your website over a secure HTTPS connection.
- The “–staple-ocsp” option enables Online Certificate Status Protocol (OCSP) stapling, which verifies an SSL certificate’s revocation status without contacting the certificate authority.
- Use the “–email” option to specify the email address you want to associate with the certificate.
- The “-d” option specifies the domain name for which you will generate the certificate. In this example, the domain name is “www.example.com.”
Alternatively, you can use the following command and follow the step-by-step prompts for a more accessible experience.
sudo certbot certonly --apache
By executing the command with the mentioned parameters, you are directing certbot to create an SSL certificate for your domain “www.example.com” while also including the necessary security features like a force HTTPS 301 redirect, Strict-Transport-Security header, and OCSP Stapling. It’s important to note that you should replace the email address in the command with your own, and also make sure to replace the domain name “www.example.com” with your desired domain name.
Configuring SSL on Apache
After obtaining the SSL certificate, configure your Apache server to use it. Edit the ssl.conf
file and add the following lines, replacing “example.com” with your domain:
sudo nano /etc/httpd/conf.d/ssl.conf
In the configuration file, add the following lines: replace “example.com” with your domain name.
SSLEngine on
SSLCertificateFile /etc/letsencrypt/live/example.com/cert.pem
SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem
Save the changes and restart Apache so the configuration takes effect.
sudo systemctl restart httpd
This setup ensures encrypted, secure communication between browsers and your website.
Automating Certificate Renewal
To keep the SSL certificate up-to-date, set up a cron job for automatic renewal. Test the renewal process with a dry run:
sudo certbot renew --dry-run
Check the timers using the systemctl list-timers command and confirm that “snap.certbot.renew.timer” is present.
systemctl list-timers snap.certbot.renew.timer
Use the command “systemctl list-timers –all” to view active and inactive timers on your system. This command overviews all timers, including the “snap.certbot.renew.timer.” The “snap.certbot.renew.timer” ensures the automatic checking and renewal of your certificate before expiration. Thus, you eliminate concerns regarding the renewal process.
systemctl list-timers --all
Apache HTTPD Management
With Apache successfully set up on your server, here are some essential points to remember for effective management.
Apache Server Logs
Apache server logs are stored in the directory at /var/log/httpd/. The default filenames for the access and error logs are access.log and error.log, respectively. However, changing these names in the virtual host configuration file is possible.
Here’s an example of changing the Apache server logs in the virtual host configuration file.
<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /var/www/example.com
# Change access log to custom-access.log
CustomLog /var/log/httpd/custom-access.log combined
# Change error log to custom-error.log
ErrorLog /var/log/httpd/custom-error.log
</VirtualHost>
This example changes the access and error logs to custom-access.log and custom-error.log, respectively. You can change the names of the log files to whatever you prefer and update the corresponding path in the virtual host configuration file.
Apache Commands
Here are some of the frequently used commands when managing Apache:
Stop Apache webserver:
sudo systemctl stop httpd
Start Apache webserver:
sudo systemctl start httpd
Restart Apache webserver:
sudo systemctl restart httpd
Reload Apache webserver:
sudo systemctl reload httpd
Disable Apache on server boot:
sudo systemctl disable httpd
Enable Apache on server boot:
sudo systemctl enable httpd
How to Update Apache HTTPD
To keep Apache updated, run the command you typically use to check if your system is up to date.
sudo dnf update --refresh
It’s important to make backups or create images of your system before performing any upgrades, as bugs can sometimes occur. The following command will refresh all system packages, including Apache, and prompt you to upgrade.
How to Remove Apache HTTPD
To uninstall Apache from your system, use the following command.
sudo systemctl disable httpd --now
Now, use the following command to remove Apache altogether.
sudo dnf remove httpd
Leftover files may persist in the /etc/httpd main directory, so let’s erase that folder.
sudo rm -R /etc/httpd/
Conclusion
With Apache HTTP Server and Let’s Encrypt successfully set up on your CentOS Stream system, your website will be both robust and secure. Regularly updating Apache and renewing your Let’s Encrypt SSL certificate will help maintain optimal security and performance. Enjoy the reliability and security that Apache HTTP Server and Let’s Encrypt bring to your web hosting environment.