Apache Server Security and Hardening

Apache Security Hardening Guide

Taking care of your Apache Security is probably one of the first things you should do after installing your web server, as it’s key to your web applications and data safety. Even before focusing on optimizations, we must prioritize security practices to prevent unauthorized access, data breaches, and vulnerabilities.

Apache is one of the most used web servers nowadays. According to the October 2024 stats provided by W3Techs, Apache’s market share is 28.7%. Also, BuiltWith reports that Apache is currently used by almost 3000 of the 10,000 most popular websites.

Apache’s huge popularity makes it a primary target for cybercriminals, so it’s important to bolster its security, and that’s why here are the top 20 strategies to harden your Apache server. We cover it all from DDoS to directory security and other HTTP security misconfigurations. Let’s get started.

Web server security is critical to protecting online applications and data from unauthorized access, use, disclosure, disruption, modification, or destruction. A web server is a software application that runs on a server and is responsible for hosting, managing, and serving websites, web applications, and other online content.

The Apache web server is one of the most popular and widely used, known for its flexibility, scalability, and security features. The Apache Project website defines it as “robust, commercial-grade, featureful, and freely-available.

Securing an Apache web server involves a combination of configuration, authentication, authorization, input validation, error handling, and logging and monitoring. A secure Apache web server configuration is essential to prevent common web attacks such as SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF). Additionally, implementing secure authentication and authorization mechanisms, validating user input, and handling errors securely can help prevent unauthorized access and data breaches.

Top 20 Apache Security Hardening Tips and Tricks

Let’s see the most popular tips for Apache security hardening.

Top 20 Apache Security Tips
Top 20 Apache Security Tips

Update Apache

Updating your web server and web servers is key to increasing your Apache security. Updates bring the latest security patches and bug fixes to prevent new vulnerabilities.

Stay informed about the latest updates and vulnerabilities with tools like stack.watch. These tools will notify you about new Apache HTTP Server vulnerabilities so you can act fast. Updating and such tools will harden your Apache server.

Hide Apache Version and OS

Hiding your web server version and OS is a simple but effective Apache security technique. By default, Apache reveals sensitive information like the server’s OS type and version which helps attackers to prepare targeted attacks.

Prevent this by modifying your httpd.conf file: set ServerTokens to Prod and disable ServerSignature. This will limit the information shared in the response headers, thus bolstering HTTP headers security and preventing server-generated documents from showing version details:

ServerTokens Prod

ServerSignature Off

This will reduce the exposure of critical server information.

Disable Directory Listing

Directory listing can expose sensitive files and directories to unauthorized users. Disable it to prevent exploitation.

Disable directory listing by setting the Options directive to -Indexes in your Apache configuration file:

Options -Indexes

This is a simple way to mitigate file exposure.

Restrict Access to Sensitive Directories

Restrict access to sensitive directories to protect your server from unauthorized users. Proper access control will only allow authorized users to access sensitive information.

To deny access to specific directories use the following directive:

Require all denied

Also, disable the mod_autoindex module globally to prevent directory listings across your Apache server. Use .htaccess files to restrict access at the directory level. For example to disable directory listing add this to your .htaccess file:

Options -Indexes

This allows you to have fine-grained control over access permissions without needing root access.

Use HTTPS Encryption

SSL security is a must. It will provide you with HTTPS encryption, which will encrypt the data transmission between your server and clients. Get an SSL certificate from a trusted Certificate Authority and then install the SSL certificate in Apache.

Update your SSL configuration files to point to the SSL certificate and key:

SSLCertificateFile /path/to/cert.pem

SSLCertificateKeyFile /path/to/key.pem

Restart Apache after making these changes. This will apply the new settings:

sudo systemctl restart apache2

This will encrypt all client requests so your web server is more secure.

Enable HTTP Strict Transport Security (HSTS)

HTTP Strict Transport Security (HSTS) will protect your website from man-in-the-middle attacks and cookie hijacking. It will force browsers to always connect to your server using HTTPS and prevent attackers from downgrading secure connections to insecure ones.

Enable HSTS by adding this to your Apache configuration:

Header always set Strict-Transport-Security “max-age=63072000; includeSubDomains”

This will enforce HTTPS for a specified time and apply the policy to all subdomains. Make sure your website is running HTTPS with a valid certificate before enabling HSTS. Restart Apache after making these changes to apply the new policy.

Disable Unused Modules

Disabling unused Apache modules will reduce the attack surface of your Apache server and optimize resource usage. Regular audits will help you identify and disable modules not required for your specific web application, and minimize the risks from HTTP misconfigurations that open up unnecessary access points.

Disable an unused module by commenting out its LoadModule line in the httpd.conf file.

Secure Apache with a Web Application Firewall (WAF)

A Web Application Firewall (WAF) like ModSecurity will add an extra layer of protection by filtering and monitoring HTTP traffic to and from your web server. It will protect against many threats including SQL injection, cross-site scripting (XSS), and more.

To use ModSecurity with Apache make sure the module is loaded in your httpd.conf file:

LoadModule security2_module modules/mod_security2.so

Include /etc/modsecurity/*.conf

ModSecurity’s main configuration file is usually in /etc/modsecurity or /etc/httpd/modsecurity.d. You may need to install additional packages for ModSecurity to work.

Implement the OWASP ModSecurity Core Rule Set (CRS) to add security with rules for common web application attacks. Also, tune ModSecurity by modifying or adding custom rules in its configuration files to suit your needs.

ModSecurity logs blocked requests in the Apache error logs so you can use that for security audits.

Run Apache as a Non-Privileged User

Running Apache as a non-privileged Apache user will protect other services in case of a breach. Isolating the Apache process from other system processes will minimize damage if compromised.

Change the default user and group settings for Apache by modifying the User and Group directives in your httpd.conf file.

User apache

Group apache

Using a dedicated, non-privileged user account for Apache will limit its access to system resources.

Limit File Upload Size

Limit file upload size to mitigate DoS attacks where large payloads can consume server resources. Configure the LimitRequestBody directive to control file upload size and prevent resource exhaustion.

Set a file upload limit by adding this to your Apache configuration:

LimitRequestBody 1048576

This will limit file uploads to 1MB and prevent resource exhaustion. Keep in mind that in some cases you may need to set a higher limit depending on your needs.

Adjust Timeout and KeepAlive

Adjust the Timeout and KeepAlive in Apache to improve security and performance. Lowering the Timeout will mitigate DoS attacks by limiting the time the server waits for client responses. The default Timeout is 300 seconds; reducing it to 60 seconds will lower the risk of Slowloris attacks.

Adjust these by modifying the httpd.conf file:

Timeout 60

KeepAlive On

MaxKeepAliveRequests 100

KeepAliveTimeout 15

This will optimize resource usage and improve server performance by allowing browsers to request multiple files without re-establishing connections each time.

Disable CGI

CGI in Apache is a big security risk, the server can be vulnerable to malicious scripts. Disabling CGI will reduce the risk and make the environment more secure.

Disable CGI by using the Options directive in the Apache configuration. Remove the ExecCGI option from the Options directive for each website hosted on the server:

Options -ExecCGI

This will prevent security vulnerabilities from executing CGI scripts.

Disabling symbolic links in Apache will reduce security risks by preventing file access through symlink traversal. This is important to protect sensitive data and server integrity.

Disable symbolic links by setting the Options directive to -FollowSymLinks in the Apache configuration file:

Options -FollowSymLinks

This will prevent Apache from following symbolic links.

IP Address Restrictions

Implement IP address restrictions in Apache to control access by specifying allowed or denied host addresses. The mod_authz_host module allows you to restrict access based on the host address of the visitor.

To restrict access use the Require directive in the Apache configuration. For example to allow specific IP addresses add:

Require ip 192.168.1.100 192.168.1.101

To block a specific IP address use:

Require not ip 192.168.1.200

This will allow you to create complex access policies and improve your Apache security.

Logging for Monitoring

Logging in Apache is important for monitoring client requests and web server performance. It will give you detailed information about server activities and help you identify potential Apache security issues.

Enable logging by including the mod_log_config module in your configuration and use the TransferLog directive to create a log file:

LogFormat “%h %l %u %t \”%r\” %>s %b” common CustomLog “/var/log/apache2/access_log” common

Important to capture in Apache access logs are the time to serve the request and SESSION ID. Conditional and forensic logging will further improve your Apache security monitoring.

Anti-Clickjacking with X-Frame-Options HTTP header

Clickjacking tricks users into clicking on something different from what they see, potentially to unintended actions. The X-Frame-Options HTTP header will prevent clickjacking by controlling if a browser can display a page in frames or iframes.

Protect against clickjacking by setting the X-Frame-Options header via HTTP headers:

Header always set X-Frame-Options “DENY”

Or use SAMEORIGIN to allow the page to be displayed only if the request is from the same site:

Header always set X-Frame-Options “SAMEORIGIN”

This will protect against clickjacking attacks.

Cookies with HttpOnly and Secure flags

Using HttpOnly and Secure flags in cookies will reduce the risk of cross-site scripting (XSS) attacks. These flags will make cookies only accessible through HTTP and not through JavaScript and only sent over secure HTTPS.

To set these flags, configure your application to use the Set-Cookie header with the HttpOnly and Secure attributes:

Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure

This will protect web application sessions and cookies from being stolen and manipulated.

Vulnerability Scanning

Vulnerability scanning is important to maintain data integrity and to ensure website data is secure from breaches. At ProtocolGuard we provide you with a free scanner that will help you identify potential Apache security holes and insecure configurations and fix them ASAP. Compared to the IIS web server, Apache has fewer vulnerabilities, but it is still crucial to patch any identified issues promptly.

  1. Access our web security scanner.
  2. Type in your domain and check the two boxes below.
  3. Hit the Scan button and wait a few seconds for the scan to complete.
Apache Security Tip: Always Check your HTTP Security Headers, and SSL configuration

Fail2ban for Intrusion Prevention

Fail2ban is an intrusion prevention tool that will protect your Apache server from external threats by monitoring logs for failed login attempts and banning the offending IPs. This will prevent brute force attacks and other malicious activities.

To configure Fail2ban, make sure it monitors the Apache log files and set the rules:

[apache]
enabled = true
port = http,https
filter = apache-auth
logpath = /var/log/apache2/*error.log
maxretry = 3

This will secure your Apache server by automatically banning IPs with repeated failed login attempts.

Apache Chroot

Chrooting Apache will add an extra layer of security by running the server in an isolated environment, limiting access to the rest of the system. This will prevent a security breach in one service from affecting others on the server.

To set up Chroot follow its documentation for the important considerations and configure the directives: 

SecChrootDir /path/to/chroot

Chrooting can be complex due to library dependencies but it’s worth it when done correctly. Using additional tools like SELinux will provide even more isolation.

To prevent .htaccess files from overriding security settings add this to your server configuration file:

AllowOverride None

To deny access to sensitive files like .htpasswd use:

Require all denied

These settings protect the sensitive parts of your server.

Advanced Security Measures

In addition to the basic Apache security measures discussed earlier, several advanced security measures can be implemented to further secure an Apache web server. These measures provide an extra layer of protection and help mitigate more sophisticated attacks.

Limit server resource consumption during Denial of Service (DoS) attacks

This can be done by configuring directives like RequestReadTimeout, TimeOut, and KeepAliveTimeout. For example:

RequestReadTimeout header=20-40,MinRate=500 body=20-60,MinRate=500
TimeOut 30
KeepAliveTimeout 5

These settings reduce the time spent waiting for client requests during DoS attacks.

Why keep Apache up to date?

Keeping Apache up to date is important for security and stability, updates will provide patches for vulnerabilities and bug fixes. Prioritizing these updates will protect your web server from threats.

How to hide the Apache version and OS?

To hide the Apache version and OS, set ServerTokens to Prod and disable ServerSignature in httpd.conf. This will remove the information from HTTP response headers and server-generated pages.

Why is HTTPS important?

HTTPS is important as it will secure the data transmission between your server and clients and protect sensitive information and overall security.

How to limit file upload size?

To limit file upload size use the LimitRequestBody directive in your Apache config. This will control the upload size manage the resource consumption and reduce the risk of DoS attacks.

What is Fail2ban and how does it help in security?

Fail2ban is an intrusion prevention tool that will enhance Apache security by monitoring logs for failed login attempts and banning the offending IPs, which will protect your server from brute force attacks and other malicious activities.

Wrapping Up

Securing your Apache server is an ongoing process and involves many strategies to protect against threats. From keeping Apache up to date to using HTTPS and HSTS, each one is important. Follow these best practices and you will harden your Apache HTTP Server, your data will be safe and your server will be smooth. Stay alert, keep learning, and always put your Apache security first in your server management.

Scroll to Top