Enable htaccess Support

The Apache HTTP Server (httpd) offers directory-level configuration through .htaccess files, which can override global settings defined in the httpd.conf file. To enable this feature, you need to adjust the AllowOverride directive in the global Apache configuration file.

By default, the AllowOverride directive is set to None to avoid performance drawbacks. This setting prevents the server from searching for .htaccess files in all parent directories and recompiling regex patterns for each request. To enable .htaccess support, simply change the AllowOverride directive to All.

AllowOverride All

The AllowOverride directive can be set to different levels, such as None, FileInfo, AuthConfig, etc. Setting it to All allows .htaccess to override any directives, but using more specific levels can limit it to only certain rules like URL rewriting or authorization.

It’s important to note that the httpd.conf file supports all rules that can be added in .htaccess files, but the reverse is not true; .htaccess files cannot support every rule available in httpd.conf. Therefore, all the rules discussed in this article will work in httpd.conf.

Pro Tip: If you plan to configure your server solely through httpd.conf or choose not to enable .htaccess due to performance concerns, it may be worth switching to the NGINX server. Nginx generally offers better performance compared to Apache. You can read our article Apache vs. NGINX to determine which server is best for your website. Additionally, check out our guide on common NGINX rules if you’re looking to implement similar configurations for Nginx.

htaccess Rule to Serve Pre-Compressed CSS and JS Files

Apache uses the mod_deflate module to compress JavaScript, CSS, and HTML files. While this module helps reduce bandwidth usage and improve metrics like First Contentful Paint (FCP) and Largest Contentful Paint (LCP) in Google’s Core Web Vitals, it also increases CPU usage because it compresses content for each request.

To mitigate high CPU usage caused by mod_deflate, you can pre-compress your CSS and JS files and configure Apache to serve them without re-compressing.

Steps to Enable Pre-Compressed Files:

  1. Pre-compress your .js and .css files and store them in the same folder as the original files, with the .gz extension. For example, index.js becomes index.js.gz, and style.css becomes style.css.gz.
  2. Add the following .htaccess rule to serve these pre-compressed files.
AddEncoding gzip .gz
<IfModule mod_rewrite.c>
    # Enable the URL rewriting engine to handle gzip content delivery.
    RewriteEngine On
    # Check if the client accepts gzip-encoded content.
    RewriteCond %{HTTP:Accept-Encoding} gzip
    # Verify if the pre-compressed file (with .gz) exists on the server.
    RewriteCond %{REQUEST_FILENAME}\.gz -f
    # Serve the pre-compressed CSS or JS file if it exists on the server.
    RewriteRule "^(.*)\.(css|js)" "$1\.$2\.gz" [QSA]
    # Set the no-gzip environment variable to prevent mod_deflate from compressing the file again.
    RewriteRule \.css\.gz$ - [T=text/css,E=no-gzip:1]
    RewriteRule "\.js\.gz$"  "-" [T=text/javascript,E=no-gzip:1]

    <FilesMatch "(\.js\.gz|\.css\.gz)$">
        # Append the Content-Encoding header to specify gzip encoding.
        Header append Content-Encoding gzip

        # Append Vary header to instruct proxies to cache the gzipped version.
        Header append Vary Accept-Encoding
    </FilesMatch>
</IfModule>

To precompress your files, you can use the gzip -k index.js command in the terminal. This will create an index.js.gz file in the same directory.

How to Use mod_deflate to Compress Files

You can use the mod_deflate module to serve gzip-compressed HTML, CSS, and JavaScript (EcmaScript) files by compressing them when requested. To use the mod_deflate module, you first need to enable it in the httpd.conf file.

# Enable deflate module in httpd.conf file
LoadModule deflate_module modules/mod_deflate.so

If you’re using a shared hosting plan, contact your hosting provider to enable this module. In most cases, hosting providers already support the mod_deflate module. Use the following .htaccess rules to compress text-based content using mod_deflate:

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

    # Fix for old browsers
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
</IfModule>

How to Add Image Hotlink Protection

Image hotlinking occurs when other websites use image URLs from your website to display images on their own sites. This practice saves the bandwidth of the other website while consuming yours, which can slow down your site and increase hosting costs.

To prevent this, it’s good practice to include .htaccess rules that block other websites from hotlinking your images. Additionally, image hotlinking can negatively affect both websites: if the original image is deleted, the other websites will have broken image links, which could harm their search engine rankings.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_REFERER} !^$
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteCond %{REQUEST_FILENAME} \.(jpe?g?|png)$ [NC]

    # Allow requests from your domain to access images.
    RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?diversifyindia.in [NC]

    # Allow Google to access images (hotlinking).
    RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?google.com [NC]

    # Block all other domains from accessing images.
    RewriteRule \.(jpe?g?|png)$ - [F,NC,L]
</IfModule>

Add Browser Caching Rules for Apache Server

Browser caching is a technique that improves web server performance by storing static assets like images, CSS, and scripts in the client’s web browser. This way, when the same client requests these assets again, they can be served directly from the browser instead of the server. This reduces bandwidth usage, decreases the number of requests to the server, and enhances overall server performance. For more details on various caching techniques, you can read our article on how to optimize web server performance. You can use either the mod_expires or mod_headers module to enable browser caching. Using mod_headers is recommended.

<IfModule mod_expires.c>
    ExpiresActive On

    # By default, do not cache any resources.
    ExpiresDefault A0

    # Set caching duration for the following file types to 1 year.
    ExpiresByType image/jpeg A31536000
    ExpiresByType image/png A31536000
    ExpiresByType image/gif A31536000
    ExpiresByType image/webp A31536000
    ExpiresByType image/avif A31536000
    ExpiresByType image/svg+xml A31536000
    ExpiresByType video/mp4 A31536000
    ExpiresByType video/webm A31536000
    ExpiresByType text/css A31536000
    ExpiresByType text/javascript A31536000
    ExpiresByType application/javascript A31536000
    ExpiresByType application/font-woff2 A31536000
    ExpiresByType application/x-font-opentype A31536000
    ExpiresByType application/x-font-truetype A31536000
</IfModule>
<IfModule mod_headers.c>
    # Set Cache-Control header to instruct browsers to cache resources for one year.
    Header set Cache-Control "max-age=31536000, public"
</IfModule>

In the caching rules, the digits followed by the letter “A” indicate the time the browser should cache a resource, measured in seconds. For example, 31536000 = 60 seconds x 60 minutes x 24 hours x 365 days, which equals one year. This means the requested resource will be cached for one year from the time it is first accessed by the client’s browser.

Note: Do not copy and paste the caching rules directly. For optimal caching, you can set different cache durations based on the type of asset. For example, CSS and JS files may be cached for longer periods (e.g., one year), while images or other media files might benefit from shorter caching periods if they change more frequently.

Block Access to PHP Files

Blocking access to PHP files is a best practice to prevent the leakage of sensitive information. If access is not restricted, PHP code will be executed whenever requested, wasting server resources and potentially exposing vulnerabilities. You can use the following rule to block access to PHP files, which will improve both your website’s security and performance. Check out our article on improving website security for more tips on resolving security issues.

<FilesMatch "\.php$">
    Require all denied
</FilesMatch>

If you need to allow access to certain PHP files like index.php, you can specify exceptions in your rule:

<FilesMatch "index.php">
    Require all granted
</FilesMatch>

Block by referer

Blocking access from spam referrers can prevent spammers from posting harmful comments on your website. You can use the following rule to block such spam referrers.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_REFERER} 4xcasino.ru [NC,OR]
    RewriteCond %{HTTP_REFERER} crypto1x1.com [NC]
    RewriteRule .* - [F]
</IfModule>

Block by User-Agent String

The user-agent blocking rule is commonly used to prevent bad bots from accessing your website, especially those that do not follow the directives in the robots.txt file. Blocking these bad bots can significantly improve your website’s performance, as they often consume high levels of resources. The following rule can be applied to block spam bots.

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_USER_AGENT} ZAP [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} AhrefsBot [NC]
    RewriteRule .* - [F]
</IfModule>

If you want to learn how to configure an Apache2 server for WordPress, read our article on properly setting up WordPress with Apache2 and PHP-FPM.

Frequently Asked Questions

How to Fix the Double Response Header Problem in Apache Server?

This issue arises when both Apache and backend scripts (e.g., PHP) try to set the same response headers, causing duplicate headers in the response, which can lead to inconsistent behavior in browsers. To fix this issue use setifempty option.

Header setifempty Cache-Control "max-age=31536000, public"

If you’re using Apache with PHP-FPM, include the always condition with the setifempty option:

Header always setifempty Cache-Control "max-age=31536000, public"

What is the Difference Between Apache2 and httpd?

httpd and apache2 refer to the same software. Some operating systems, such as Red Hat-based distros (CentOS, Fedora), use the term httpd, while Debian-based distros (Ubuntu) refer to it as apache2.

How to Restart Apache Server?

On Debian-based distributions (like Ubuntu), you can use the service or systemctl command to restart the Apache2 server:

sudo service apache2 restart
# OR
sudo systemctl restart apache2.service

On Alpine Linux, use the rc-service command:

sudo rc-service apache2 restart

The service command is an older method used for managing services, while systemctl is part of systemd, which is now standard on most modern Linux distributions. Alpine Linux, however, uses OpenRC, where services are managed using rc-service.

How to Automatically Start Apache Server on Every Reboot?

To enable Apache to start automatically on every reboot, use the systemctl command:

sudo systemctl enable apache2.service

On Alpine Linux, use the rc-update command to add the service to the default runlevel:

sudo rc-update add apache2 default