Menu Close

27 WordPress .htaccess Tips for Better Security and Performance — Part 3: Advanced Redirects, Bot Protection, and Website Optimization

Enter example and select .com. Results and checkout open in the HostsDepot store.

In Parts 1 and 2 of this series, we explored 18 practical .htaccess techniques for WordPress security, performance, and server configuration.

We covered sensitive file protection, administrative access restrictions, browser caching, PHP configuration, and directory management.

In this final installment, we will introduce nine additional techniques that help administrators manage HTTPS connections, control unwanted traffic, protect website resources, customize error pages, and improve file delivery.

These techniques are particularly useful for WordPress websites hosted on Apache HTTP Server.

However, not every setting is appropriate for every website. Some configurations may already be handled by WordPress plugins, hosting providers, or content delivery networks.

The following examples are primarily designed for Apache HTTP Server 2.4. Always back up your .htaccess file before making changes.

Tip 19. Redirect HTTP Requests to HTTPS

HTTPS encrypts communication between a visitor’s browser and your website.

It helps protect information transmitted across the network and allows browsers to verify the server’s identity through its TLS certificate.

Modern WordPress websites should generally use HTTPS for all public pages, not just login and checkout pages.

If your website has a valid SSL/TLS certificate, Apache can redirect ordinary HTTP requests to HTTPS.

For a straightforward Apache installation that directly handles incoming client connections, you can use:

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://example.com%{REQUEST_URI} [R=301,L]
</IfModule>

Replace example.com with your own domain name.

The RewriteCond directive checks whether the connection to Apache is using HTTPS.

If HTTPS is not enabled, the RewriteRule directive redirects the request to the specified HTTPS URL.

The R=301 flag sends a permanent redirect, while the L flag stops further rewrite processing in the current pass.

For example:

http://example.com/tutorial/

becomes:

https://example.com/tutorial/

However, websites using Cloudflare, reverse proxies, or load balancers require additional consideration.

Apache may receive an internal HTTP connection even when the visitor originally connected using HTTPS.

In those environments, blindly checking the HTTPS variable can create an infinite redirect loop.

If your hosting provider or CDN already handles HTTPS redirection, it is usually better to use that existing configuration rather than introduce another competing redirect.

Also confirm that the WordPress Address and Site Address settings use the intended HTTPS URLs.

Tip 20. Change the Default Directory Index

When a visitor requests a website directory, Apache looks for a default index resource.

Common examples include:

index.html

index.php

default.html

On WordPress websites, index.php is normally the main entry point for processing requests.

Apache uses the DirectoryIndex directive to determine which files should be considered directory index resources.

For example:

DirectoryIndex index.php index.html

This tells Apache to look for index.php first and index.html second.

If both files exist in the same directory, Apache normally selects index.php because it appears first.

You can also configure a different order:

DirectoryIndex index.html index.php

In that case, an existing index.html file takes priority.

This can be useful when temporarily replacing a dynamic homepage with a static page or when configuring a custom application.

However, changing the default index order on a WordPress website may cause unexpected behavior.

For example, an old index.html file left in the document root could prevent WordPress from displaying its normal homepage.

For most WordPress installations, keeping index.php as the primary directory index is appropriate.

If your intention is to display a temporary maintenance page, consider a proper HTTP 503 maintenance configuration rather than simply replacing the website’s index file.

Tip 21. Block Unwanted Bots and Website Scrapers

Automated programs constantly visit websites for many different purposes.

Some are legitimate search engine crawlers that index publicly available content. Others collect information, scan for vulnerabilities, or generate excessive unwanted traffic.

WordPress websites may receive requests from automated tools looking for outdated plugins, exposed configuration files, or common administration endpoints.

Apache can filter requests based on their User-Agent header.

For example:

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{HTTP_USER_AGENT} (?:BadBot|ExampleScraper|SiteRipper) [NC]
RewriteRule ^ - [F,L]
</IfModule>

This example rejects requests whose User-Agent contains one of the specified strings.

The NC flag makes matching case-insensitive.

The F flag returns HTTP 403 Forbidden.

Replace these example identifiers with actual unwanted User-Agent patterns identified in your server logs.

However, User-Agent filtering has an important limitation: the header is controlled by the client and can easily be changed or forged.

A malicious scraper can identify itself as an ordinary browser or impersonate a well-known search engine crawler.

Therefore, User-Agent blocking should not be considered a reliable method of identifying malicious traffic.

Avoid blocking legitimate search engine crawlers without a clear reason. Doing so can negatively affect website discovery and indexing.

For WordPress websites experiencing substantial automated traffic, use a web application firewall, rate limiting, and request analysis rather than maintaining an extensive User-Agent blacklist in .htaccess.

Tip 22. Prevent Image Hotlinking

Image hotlinking occurs when another website displays an image directly from your server instead of hosting its own copy.

For example, another website might use the following HTML image reference:

<img src="https://example.com/images/photo.jpg">

When visitors open that external website, their browsers request the image from your server.

This can consume bandwidth and server resources without bringing those visitors directly to your website.

Apache mod_rewrite can discourage this behavior by examining the HTTP Referer header.

For example:

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com(?:/|$) [NC]
RewriteRule \.(jpg|jpeg|png|gif|webp)$ - [F,L,NC]
</IfModule>

Replace example.com with your domain name.

The first condition allows requests that contain no Referer header.

The second condition checks whether the referring page belongs to your website.

The final rule denies matching image requests when their Referer header indicates an unauthorized external source.

Allowing an empty Referer is important because legitimate browsers, privacy tools, and applications may omit this header.

However, Referer-based filtering is not a strong security mechanism. The Referer header can be missing or deliberately modified.

Hotlink protection can also interfere with search engine image previews, feed readers, external applications, and authorized embedding.

If your website uses Cloudflare or another CDN, check whether its hotlink protection feature is more suitable for your hosting environment.

Tip 23. Block Spam Referrers

Website administrators sometimes discover suspicious referral sources in their access logs or analytics reports.

These sources may be associated with automated requests, spam campaigns, or attempts to manipulate website analytics.

Apache allows administrators to reject requests containing selected Referer values.

For example:

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{HTTP_REFERER} (?:spam-site\.example|fake-referrer\.example) [NC]
RewriteRule ^ - [F,L]
</IfModule>

This configuration blocks requests when the Referer header contains either of the specified patterns.

The example domains are placeholders and should be replaced only when you have a justified reason to block particular sources.

However, there is an important distinction between unwanted HTTP requests and referral spam appearing in analytics.

Some analytics referral spam does not involve a normal visit to your Apache website at all. In those cases, .htaccess rules cannot eliminate the unwanted analytics entries.

Even when actual requests reach Apache, attackers can forge or omit Referer headers.

For this reason, referrer filtering is best treated as a narrow traffic-management technique rather than a comprehensive anti-spam solution.

For persistent unwanted traffic, a firewall or CDN rule based on multiple signals is usually more effective.

Tip 24. Create Custom Error Pages

When a website encounters an error, Apache normally returns an HTTP response code indicating what happened.

Common status codes include:

403 Forbidden — The server refuses access to the requested resource.

404 Not Found — The requested resource cannot be found.

500 Internal Server Error — The server encountered an unexpected condition.

503 Service Unavailable — The server is temporarily unable to handle the request.

You can customize some Apache-generated error responses using the ErrorDocument directive.

For example:

ErrorDocument 403 /errors/403.html
ErrorDocument 404 /errors/404.html
ErrorDocument 500 /errors/500.html

These directives tell Apache to use the specified local documents when generating the corresponding errors.

Create the error pages inside the appropriate directory.

For example:

public_html/errors/404.html

A useful custom 404 page should explain that the requested resource could not be found and provide a clear way to return to the website.

You might include a homepage link, search function, or navigation menu.

However, WordPress already supports custom 404 pages through its theme system.

For ordinary missing WordPress posts and pages, customizing the WordPress 404 template is usually preferable.

The Apache ErrorDocument configuration is particularly useful for server-generated errors that occur outside normal WordPress routing.

Avoid external redirects for ordinary error documents because they may change the response status and confuse clients or search engines.

Also remember that a custom error page should not reveal sensitive server information, internal paths, or application debugging details.

Tip 25. Implement Advanced URL Redirects

Website administrators often need more flexible redirect rules than simple one-to-one URL mappings.

For example, you may want to redirect an entire directory, change an old URL pattern, or move a collection of tutorials to a new location.

Apache mod_rewrite supports regular expressions that can match and transform requested URLs.

Suppose your website previously stored tutorials under:

https://example.com/old-guides/

You now want to move them to:

https://example.com/tutorials/

You can use:

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteRule ^old-guides/(.*)$ /tutorials/$1 [R=301,L]
</IfModule>

The regular expression matches requests beginning with old-guides/.

The parentheses capture the remaining portion of the URL.

The $1 reference inserts the captured portion into the destination.

For example:

https://example.com/old-guides/apache.html

will redirect to:

https://example.com/tutorials/apache.html

The HTTP 301 status tells clients that the resource has permanently moved.

Before enabling this rule, verify that the destination pages actually exist and use the expected directory structure.

A rewrite rule that redirects to nonexistent pages creates a poor user experience and may produce additional errors.

For WordPress migrations, coordinate redirect rules with the site’s permalink configuration.

Place custom rewrite rules outside WordPress-managed markers, and test carefully for conflicts.

Avoid creating loops in which the destination matches the same redirect condition repeatedly.

Tip 26. Force Browsers to Download Media Files

Modern browsers can display many file formats directly, including PDF documents, JPEG images, MP3 audio, and MP4 videos.

However, some website owners prefer visitors to download these files rather than view or play them in the browser.

Apache can influence this behavior through the Content-Disposition response header.

For example, to instruct browsers to download PDF files, add:

<IfModule mod_headers.c>
<FilesMatch "(?i)\.pdf$">
    Header set Content-Disposition "attachment"
</FilesMatch>
</IfModule>

This tells browsers to treat matching PDF resources as downloadable attachments.

You can extend the rule to several media types:

<IfModule mod_headers.c>
<FilesMatch "(?i)\.(pdf|mp3|mp4|zip)$">
    Header set Content-Disposition "attachment"
</FilesMatch>
</IfModule>

This configuration covers PDF documents, MP3 audio, MP4 video, and ZIP archives.

For example, a visitor requesting:

https://example.com/downloads/linux-guide.pdf

will generally be prompted to download the PDF or have it saved according to browser settings.

However, do not apply this rule indiscriminately to files that WordPress needs to display within webpages.

For example, forcing images or videos to download may interfere with media previews or embedded players.

A safer approach is to create a dedicated downloads directory and configure the attachment header only within that directory.

For example, inside:

public_html/downloads/.htaccess

you can add:

<IfModule mod_headers.c>
Header set Content-Disposition "attachment"
</IfModule>

This instructs browsers to download resources served from that directory, subject to normal browser behavior and any overriding application headers.

Remember that Content-Disposition does not restrict access. Publicly accessible files remain accessible to anyone who knows their URLs.

Tip 27. Block Selected Suspicious Characters in URL Requests

Some automated attacks use unusual URL sequences, encoded control characters, or manipulated path representations to test website vulnerabilities.

Examples include requests containing encoded null bytes or certain encoded line-ending characters.

Although such sequences may indicate suspicious activity, not every special character is malicious.

Modern websites use URL encoding for spaces, international text, and ordinary query parameters.

For example:

%20

represents a space and is commonly used in valid URLs.

Blindly blocking all percent-encoded characters would interfere with legitimate website functionality.

A better approach is to reject narrowly defined patterns that your application does not expect.

For example:

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{THE_REQUEST} "%(00|0A|0D|7F)" [NC]
RewriteRule ^ - [F,L]
</IfModule>

This example examines the original HTTP request line and looks for selected encoded control characters.

The THE_REQUEST variable contains the original request line received by Apache.

The rule checks for percent-encoded null, line feed, carriage return, and delete characters.

When a matching sequence is found, Apache returns HTTP 403 Forbidden.

However, malformed requests may already be rejected by Apache before .htaccess processing.

This rule is only a targeted additional filter. It does not identify every malicious request or prevent all injection attacks.

Do not assume that special-character filtering replaces secure application coding.

WordPress and its plugins must still validate input, properly escape output, use parameterized database queries, and enforce authorization.

A properly configured web application firewall can provide broader inspection and protection against common attack patterns.

How to Test the Rules in Part 3

Before deploying these techniques on a production WordPress website, test the configuration in a staging environment whenever possible.

You should verify that ordinary pages, media resources, WordPress administration functions, and important plugin features continue to operate normally.

The curl command is particularly useful for examining HTTP responses.

To inspect a webpage:

curl -I https://example.com/

To test a redirect:

curl -I http://example.com/

Look for the Location response header and an appropriate HTTP redirect status.

To test a custom 404 page:

curl -I https://example.com/page-that-does-not-exist

For a correctly configured missing resource, the server should normally return HTTP 404 rather than HTTP 200.

To inspect a media download header:

curl -I https://example.com/downloads/manual.pdf

Look for:

Content-Disposition: attachment

If you encounter an HTTP 500 Internal Server Error after editing .htaccess, restore the previous file and review Apache’s error logs.

A missing module, unsupported directive, or syntax mistake may cause the configuration to fail.

Apply rules individually instead of copying all configurations into a production website at once.

Which .htaccess Rules Should Every WordPress Website Use?

Not all 27 techniques in this series are necessary for every WordPress installation.

For most Apache-based WordPress websites, a practical starting point is to protect sensitive configuration files, disable unnecessary directory listings, ensure HTTPS is correctly configured, and establish appropriate browser caching for static resources.

Administrators should also maintain secure file permissions and avoid allowing user-uploaded files to execute as server-side scripts.

Other techniques depend on your website’s specific requirements.

For example, IP restrictions may be useful for a private administrative website but inconvenient for a public site managed from multiple locations.

Hotlink protection may help websites hosting large image collections but could interfere with legitimate media sharing.

Custom redirect rules are useful during website migrations but unnecessary for sites whose URL structures have not changed.

The best configuration is not necessarily the one containing the largest number of directives.

It is the configuration that provides appropriate protection without introducing compatibility problems or unnecessary maintenance.

Beyond .htaccess: Building a More Secure WordPress Website

Although .htaccess provides useful server-level controls, WordPress security requires a broader approach.

Keep WordPress core, themes, plugins, PHP, and the operating system updated to supported versions.

Remove unnecessary plugins and themes to reduce the attack surface.

Protect administrator accounts with strong passwords and multifactor authentication.

Maintain reliable offsite backups and periodically test restoration procedures.

Use a web application firewall to help detect common web attacks.

Review access logs and application logs for unusual activity.

For performance, combine appropriate browser caching with server-side page caching, optimized images, efficient database queries, and suitable hosting resources.

If your website uses Cloudflare or another CDN, understand which security and performance controls are already implemented at the edge.

Avoid duplicating rules unnecessarily across Apache, WordPress plugins, and CDN configurations.

Conclusion: 27 WordPress .htaccess Tips

Throughout this three-part series, we have examined 27 practical techniques for improving WordPress security, performance, and website administration.

Part 1 introduced essential WordPress protection, including configuration file security, administrative access restrictions, directory protection, browser caching, and PHP settings.

Part 2 explored advanced caching, URL redirects, sensitive configuration files, server signatures, timezone settings, directory management, and script execution restrictions.

Part 3 completed the series with HTTPS configuration, directory indexes, unwanted bot filtering, hotlink protection, spam referrers, custom error pages, advanced redirects, media downloads, and suspicious URL filtering.

Together, these techniques demonstrate how Apache .htaccess can help website administrators control how requests are handled and how resources are delivered.

However, security and performance improvements should always be guided by your actual hosting environment and application requirements.

A small number of carefully tested rules can be more valuable than a complicated configuration containing unnecessary or conflicting directives.

For modern WordPress websites, the most effective approach combines secure Apache configuration, updated software, strong authentication, reliable backups, efficient caching, and continuous monitoring.

Leave a Reply

Your email address will not be published. Required fields are marked *