Sign In
Sign In

How to Install Apache on CentOS

How to Install Apache on CentOS
Hostman Team
Technical writer
Apache CentOS
11.11.2024
Reading time: 8 min

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=http
sudo 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 httpd
sudo 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.

  1. Create the html directory for example.com:

sudo mkdir -p /var/www/example.com/html
  1. Create a directory for log files:

sudo mkdir -p /var/www/example.com/log
  1. Set permissions for the html directory. Assign ownership to the $USER environment variable.

sudo chown -R $USER:$USER /var/www/example.com/html
  1. Verify standard permissions for the root directory:

sudo chmod -R 755 /var/www
  1. 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.

  1. 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.

Apache CentOS
11.11.2024
Reading time: 8 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 Disable Directory Browsing on Apache

When using an Apache server, directory browsing creates a security issue since it allows unauthorized users to view the organization and contents of your website's directories. Directories without an index file, such as index.html or index.php, may by default allow users to view their contents through Apache. Directories without an index file, such as index.html or index.php, may by default allow users to view their contents through Apache. This feature is considered by many as a terrible practice for production servers, despite the fact that it can be helpful in some development contexts. In order to improve the safety features of the website and prevent unauthorized access to vital information, one should take the easy but crucial action of disabling directory browsing on the website's server. This tutorial will show how to prevent directory surfing on an Apache web server, so that directories stay hidden from the attackers.  Prerequisites A cloud server with installed and running Apache Access to the Apache Server  Understanding Directory Browsing in Apache When no specified file (like index.html or index.php) is present to be displayed as the default page, the web server can show the contents of a directory. This is known as directory browsing in Apache. Users who have directory browsing enabled can view a list of files and folders within a directory by navigating to a URL that matches a directory path on the server.  Depending on how the server is configured, directory browsing may or may not be enabled by default for Apache. The Apache configuration files' Options directive manages this behavior. The Indexes option there establishes whether directory browsing is permitted. Directory browsing will be available for the designated directories if the Indexes option is included in the configuration. Directory browsing presents a number of risks in a production setting, even though it may be helpful for some types of file repositories or during development. Users may end up with access to private information—like configuration files, backup files, or temporary files—that were not intended to be shared with the public. Leaving a directory structure exposed could lead to the discovery of security flaws like outdated script versions, incorrect setups, or files containing known vulnerabilities. Directory browsing could be used by unauthorized users to obtain information for a more focused attack on the system or to download things that need to be kept secret. Disabling Directory Browsing in the Main Configuration File It's simple to disable directory browsing in the Apache main configuration file by changing the Options directive to make sure the Indexes option is disabled. This directive determines how directories behave in a number of ways, such as whether directory browsing is permitted. By modifying the primary Apache configuration file, you can turn off directory browsing as follows: Depending on your operating system, the primary Apache configuration file is normally found in one of the following directories: Debian/Ubuntu /etc/apache2/apache2.conf CentOS/RHEL /etc/httpd/conf/httpd.conf Make a backup on the configuration file above by running the command below. sudo cp -rp /etc/apache2/apache2.conf /etc/apache2/apache2.conf.backup Open the file and edit it with a text editor such as Vim or Nano. nano /etc/apache2/apache2.conf Find the Directory Configuration Block. There are multiple blocks in the configuration file. These blocks specify configurations for particular server folders. The root directory is the highest-level directory on the server, and the settings in the block are applicable to it. Look for a block that is similar to the following:Within this block look for the line that contains Options (box in red).  It may include the Indexes option, which enables directory browsing. Remove the Indexes option from the Options directive to disable the directory browsing. This is how the modified directive should appear. Save and exit on the editor.  For changes to take effect, restart the Apache service. Run the command below. Debian/Ubuntu sudo systemctl restart apache2 Centos/RHEL sudo systemctl restart httpd Verify that directory browsing has been disabled in order to validate the modifications. Then, use a web browser to access a directory on the server without an index file. Users should get a "403 Forbidden" response instead of a directory listing, indicating that directory browsing is no longer permitted. Disabling Directory Browsing in Virtual Host Files With Apache, different websites may be operated; each with its own configuration, on a single server by using virtual hosts. One can change the configuration in the virtual host files to prevent directory browsing for particular websites or virtual hosts. Here's how to make this happen: Depending on your operating system, the primary Apache configuration file is normally found in one of the following directories: Debian/Ubuntu /etc/apache2/sites-available/ CentOS/RHEL /etc/httpd/conf.d/ or /etc/httpd/sites-available/ Every virtual host will have a configuration file of its own, usually called example.com.conf or after the domain or website it serves. Make a backup on the configuration file above by running the command below. sudo cp  /etc/apache2/sites-available/example.com.conf  /etc/apache2/sites-available/example.com.conf.backup Open the file above and edit it with a text editor such as Vim or Nano. nano /etc/apache2/sites-available/example.com.conf Find the Directory Configuration Block. There are multiple blocks in the configuration file. These blocks specify configurations for particular server folders. The root directory is the highest-level directory on the server, and the settings in the block are applicable to it. Look for a block that is similar to the following:Within this block look for the line that contains Options (box in red).  it may include the Indexes option, which enables directory browsing. Remove the Indexes option from the Options directive to disable the directory browsing. This is how the modified directive should appear. Save and exit on the editor.  For changes to take effect, restart the Apache service. Run the command below. Debian/Ubuntu sudo systemctl restart apache2 Centos/RHEL sudo systemctl restart httpd Verify that directory browsing has been disabled in order to validate the modifications. Then, use a web browser to access a directory on the server without an index file. Users should get a "403 Forbidden" response instead of a directory listing, indicating that directory browsing is no longer permitted. Disabling Directory Browsing Using .htaccess Files With Apache, the.htaccess file is a strong configuration tool that lets users change server settings for individual directories. One can change or create a.htaccess file in the directory where they wish to apply this setting if they don't have access to the main Apache configuration file or if they want to block directory browsing for a particular directory. Using a.htaccess file, users can prevent directory browsing as follows: To disable directory browsing, navigate to the desired directory. This could be any subdirectory inside the site itself or the document root of the website (/var/www/example.com, for example). cd /var/www/example.com If there's already a .htaccess file in the directory, one can edit it with a text editor. Otherwise, one can make a fresh .htaccess file sudo nano .htaccess Add the line below on the file then save and exit. Options -Indexes Apache needs to be set up to permit .htaccess overrides in the appropriate directory in order for the .htaccess file to function. The AllowOverride directive in the virtual host or Apache configuration files controls this. Verify that the virtual host file or directory block in the Apache configuration permits overrides, as shown below. Verify that directory browsing has been disabled in order to validate the modifications. Then, use a web browser to access a directory on the server without an index file. Users should get a "403 Forbidden" response instead of a directory listing, indicating that directory browsing is no longer permitted. Troubleshooting Common Issues Although it is usually simple to disable directory browsing on Apache, there are certain issues that make the setup not work as intended. Users can solve typical problems while deactivating directory browsing on Apache by checking the list of solutions provided below. Directory browsing remains enabled even after making changes to the. htaccess file or Apache settings. To make the modifications take effect, make sure to restart the Apache server. Use the command that is right for your operating system. Debian/Ubuntu sudo systemctl restart apache2 CentOS/RHEL sudo systemctl restart httpd Check to see if the Apache user is allowed to view the modified configuration files or the .htaccess file. These files may not be readable by Apache due to incorrect file permissions. Perform the following if issue has been encountered. sudo chmod 644 /path/to/.htaccess Debian/Ubuntu sudo chown www-data:www-data /path/to/.htaccess   CentOS/RHEL sudo chown apache:apache /path/to/.htaccess Users get a "403 Forbidden" error for all requests after disabling directory browsing, even when trying to access files that are supposed to be available. To enable Apache to serve files, make sure the directory permissions are set appropriately. Run the command to fix it. sudo chmod 755 /var/www/example.com Make sure the AllowOverride directive in the Apache configuration is set to All, or at the very least, to allow the Options directive, especially if users are using a.htaccess file. After changing the configuration to deactivate directory browsing, Apache either fails to start or restarts with issues. Before restarting Apache, run a syntax check on the configuration files to identify any errors. sudo apachectl configtest For more details on the reason why Apache is not starting, review the Apache error logs. Debian/Ubuntu sudo tail -f /var/log/apache2/error.log  CentOS/RHEL sudo tail -f /var/log/httpd/error_log CONCLUSION One of the most important things one can do to secure the web server is to disable directory browsing on Apache. The directories' contents can be kept hidden from unauthorized users, lowering the possibility of vulnerable information and sensitive data being exposed. Using.htaccess files, virtual host file adjustments, and changes to the main Apache configuration file are some of the methods available to stop directory browsing. There is flexibility in each option based on the server configuration and access level. Knowing how to limit directory browsing at different levels is important for those who oversee a single site or a number of virtual hosts. It guarantees that the server is safe and properly setup. Even though the procedure is normally simple, be ready to troubleshoot common problems to make sure the modifications are implemented correctly, such as wrong permissions, conflicting setups, or syntax errors. These actions will help to safeguard information, improve the security of the Apache server, and give users a safer environment. Maintaining a strong and secure online infrastructure includes routinely checking and updating the server's settings, as well as turning off pointless functions like directory browsing.
05 September 2024 · 9 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