WordPress is one of the most widely used content management systems, powering everything from personal blogs to business websites and online stores. However, maintaining a secure and efficient WordPress website requires more than installing themes, updating plugins, and choosing a reliable hosting provider.

Click to WordPress Web Hositng from $7.47 per month
For WordPress websites running on Apache HTTP Server, the .htaccess file provides a powerful way to control how the server handles incoming requests. It can help protect sensitive files, manage access permissions, configure URL rewriting, and improve website performance.
In this three-part series, we will explore 27 practical WordPress .htaccess techniques, focusing on security, performance, and server administration.
Part 1 introduces nine essential techniques, from configuring WordPress permalinks to protecting critical files, restricting unwanted access, and managing PHP settings.
The examples are designed primarily for Apache HTTP Server 2.4. Before applying any configuration, verify that your hosting environment supports the required directives.
Understanding the WordPress .htaccess File
The .htaccess file is an Apache directory-level configuration file. It allows administrators to apply certain server settings without directly modifying the main Apache configuration.
On many cPanel hosting accounts, the main WordPress .htaccess file is located at:
public_html/.htaccess
Because the filename begins with a period, it may be hidden in your file manager. Enable Show Hidden Files if necessary.
WordPress automatically maintains a section of this file for permalink rewriting. That section is normally marked by BEGIN WordPress and END WordPress comments.
Custom configuration rules should be placed outside the WordPress-managed section because WordPress may regenerate its own rewrite directives.
Before editing .htaccess, always save a backup copy. An invalid directive or unsupported setting can cause an HTTP 500 Internal Server Error.
Apache also recommends using the main server configuration instead of .htaccess when you have full administrative control, because distributed configuration files introduce additional filesystem checks and configuration-processing overhead.
For shared hosting customers, however, .htaccess remains a convenient and widely supported option.
Tip 1. Configure WordPress Permalinks Correctly
WordPress supports human-readable URLs, commonly called pretty permalinks.
Without permalink rewriting, a WordPress article may use an address such as:
With pretty permalinks enabled, the same article may use:
https://example.com/linux-server-security/
The second address is easier to read, share, and organize.
Apache’s mod_rewrite module allows WordPress to use these descriptive URLs even when no corresponding physical directory or file exists.
A typical WordPress installation in the website root uses the following rules:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
The RewriteEngine directive enables URL rewriting.
The first RewriteRule prevents index.php from being rewritten unnecessarily.
The two RewriteCond directives check whether the requested URL corresponds to an existing file or directory.
If neither exists, Apache internally directs the request to index.php, allowing WordPress to determine which content should be displayed.
This is an internal rewrite rather than an HTTP redirect. Visitors continue seeing the original URL in their browsers.
To configure permalinks, open your WordPress dashboard, navigate to Settings → Permalinks, and choose your preferred structure.
For most websites, the Post name structure provides clean, readable URLs.
Avoid manually editing the WordPress-managed rewrite block unless you understand how WordPress routing works.
Tip 2. Protect the WordPress Login Page
The WordPress login page is commonly located at:
https://example.com/wp-login.php
Because this address is widely known, automated tools frequently target it with password-guessing attempts.
For websites administered from a fixed public IP address, Apache can restrict access to the login page.
Add the following rule to the main .htaccess file:
<Files "wp-login.php">
Require ip 203.0.113.10
</Files>
Replace the example IP address with your actual public IP address.
If several administrators need access, specify multiple approved addresses:
<Files "wp-login.php">
Require ip 203.0.113.10 198.51.100.20
</Files>
This allows requests from either of the specified addresses.
However, this technique is not suitable for every WordPress website.
If administrators frequently change networks or use dynamic residential IP addresses, they may accidentally lock themselves out.
WordPress websites behind Cloudflare or another reverse proxy also require correctly configured client IP handling.
Restricting the entire wp-admin directory is more complicated because some plugins and themes use admin-ajax.php and admin-post.php for public-facing features.
For that reason, login-page restrictions are generally easier to manage than broad wp-admin restrictions.
For websites where IP filtering is impractical, use strong passwords, multifactor authentication, login rate limiting, and a properly configured web application firewall.
IP filtering should be considered an additional security layer, not a replacement for authentication.
Tip 3. Block Known Abusive IP Addresses
Apache access logs can reveal repeated suspicious activity from particular IP addresses.
For example, a visitor may repeatedly request nonexistent PHP files, scan for vulnerable plugins, or generate excessive requests.
If you identify an abusive IP address, you can block it through .htaccess.
For example:
<RequireAll>
Require all granted
Require not ip 198.51.100.25
</RequireAll>
This rule permits ordinary visitors while denying requests from the specified address.
To block several addresses:
<RequireAll>
Require all granted
Require not ip 198.51.100.25
Require not ip 203.0.113.50
</RequireAll>
You can also block a subnet when there is a clear operational reason.
For example:
<RequireAll>
Require all granted
Require not ip 198.51.100.0/24
</RequireAll>
However, subnet blocking may affect legitimate visitors who share the same address range.
Be especially careful when your website operates behind Cloudflare or another reverse proxy. Apache must be configured to recognize the actual client IP addresses from trusted proxies.
Never trust arbitrary client-supplied forwarding headers without appropriate proxy configuration.
For large-scale attacks, firewall-level or CDN-level filtering is generally more effective than maintaining numerous IP restrictions in .htaccess.
Use Apache IP blocking for limited, clearly identified cases.
Tip 4. Protect the .htaccess File
The .htaccess file contains Apache configuration directives that may reveal information about your website’s server behavior, access restrictions, and URL structure.
Apache normally prevents direct HTTP access to .htaccess files through its default configuration.
Nevertheless, you can explicitly deny HTTP requests for this file.
Add:
<Files ".htaccess">
Require all denied
</Files>
This tells Apache to reject direct requests for .htaccess.
The server can still read and process the file internally.
The protection does not prevent someone with filesystem access from reading or modifying it, so proper ownership and permissions remain important.
On many Linux hosting environments, regular website files commonly use permissions such as 644, although appropriate settings depend on the server’s ownership model.
Avoid making configuration files writable by everyone.
An attacker who obtains permission to modify .htaccess may be able to redirect visitors, interfere with application routing, or change security controls.
Tip 5. Protect the wp-config.php File
The wp-config.php file contains essential WordPress configuration information.
This includes database connection settings, authentication salts, and other application configuration values.
If the contents of this file become publicly accessible, attackers may obtain information that could help compromise the WordPress installation.
You can explicitly block direct HTTP access using:
<Files "wp-config.php">
Require all denied
</Files>
Apache will reject direct requests for the file while allowing PHP to load it internally.
This is an additional precaution. Under normal circumstances, properly configured PHP handling already prevents visitors from seeing the PHP source code.
However, server misconfiguration can sometimes expose sensitive files.
Protecting wp-config.php helps reduce this risk.
You should also ensure that its filesystem permissions are appropriate for your hosting environment.
Where supported, WordPress can use a configuration file located outside the publicly accessible document root.
Remember that protecting wp-config.php does not replace database security, secure credentials, or reliable backups.
Tip 6. Prevent PHP Execution Through the Uploads Directory
The WordPress wp-content directory contains plugins, themes, and uploaded media.
One particularly important subdirectory is:
wp-content/uploads/
This directory normally stores images, PDF documents, audio files, and videos uploaded through WordPress.
Because it contains user-supplied content, it deserves special security attention.
Under normal circumstances, media files should not execute as server-side PHP programs.
If an attacker exploits a vulnerable upload function, they may attempt to place a malicious PHP script inside the uploads directory.
A useful additional protection is to deny HTTP access to selected executable file extensions.
Create a separate .htaccess file inside:
public_html/wp-content/uploads/
Add:
<FilesMatch "(?i)\.(php|php[0-9]+|phtml|phar)$">
Require all denied
</FilesMatch>
This rule blocks direct HTTP requests for filenames ending in the specified PHP-related extensions.
Ordinary image formats such as JPG, PNG, GIF, and WebP remain accessible.
However, this rule is not a complete guarantee against script execution.
The PHP handler and web server configuration must also prevent uploaded files from being treated as executable scripts.
The strongest protection is to configure upload directories as non-executable at the server level.
In addition, WordPress and its plugins must validate uploads, restrict permissions, and prevent unauthorized file creation.
Do not block the entire wp-content directory. WordPress needs to serve themes, stylesheets, scripts, and media files from this location.
Tip 7. Protect WordPress Internal PHP Files
WordPress includes PHP files that are intended primarily for internal application use rather than direct requests from website visitors.
Many of these files are located inside:
wp-admin/includes/
wp-includes/
These directories contain WordPress libraries, supporting functions, and other core components.
However, administrators should not simply block every PHP file in these directories.
Some WordPress components and integrations may legitimately access particular endpoints, and overly broad restrictions can cause compatibility problems.
For a standard single-site WordPress installation, a narrowly targeted rule can protect the wp-admin/includes directory.
Add the following above the WordPress-managed rewrite section:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^wp-admin/includes/ - [F,L]
</IfModule>
This rule denies direct requests whose paths begin with wp-admin/includes/.
The F flag returns HTTP 403 Forbidden.
The L flag stops further rewrite processing in the current pass.
WordPress itself can still include PHP files internally through normal filesystem operations.
However, this is an optional hardening measure rather than a requirement for every WordPress website.
For wp-includes, avoid applying a blanket PHP-file restriction unless you have verified that your WordPress version, plugins, and integrations do not require direct access to the affected resources.
WordPress Multisite installations may also have additional compatibility requirements.
Protecting internal files should never come at the expense of breaking legitimate application behavior.
The most important protections remain correct filesystem permissions, updated WordPress software, and secure application configuration.
Tip 8. Enable Browser Caching for Static Resources
Browser caching allows visitors to reuse previously downloaded resources rather than retrieving the same files repeatedly from the server.
This can reduce bandwidth usage and improve repeat-visit loading times.
WordPress websites commonly serve static resources such as images, stylesheets, JavaScript files, and web fonts.
Apache provides caching controls through the mod_expires module.
For example:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType image/webp "access plus 1 month"
ExpiresByType image/avif "access plus 1 month"
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
ExpiresByType font/woff2 "access plus 1 year"
</IfModule>
These rules configure caching lifetimes based on the Content-Type of each resource.
For example, the image directives configure a one-month freshness lifetime.
CSS and JavaScript resources receive a one-week freshness lifetime.
WOFF2 font files receive a one-year freshness lifetime.
The longer font caching period is most appropriate for versioned files that are not modified while retaining the same URL.
Caching can improve website performance, but overly aggressive caching may cause visitors to receive outdated resources.
If you frequently update a stylesheet or image without changing its URL, choose an appropriate shorter cache duration or implement reliable cache-busting.
Also check whether your hosting provider, WordPress caching plugin, or CDN already manages browser caching.
Avoid adding multiple conflicting caching configurations.
Browser caching is different from WordPress page caching. Browser caching stores reusable resources on the visitor’s device, while page caching can reduce server-side PHP and database processing.
Both techniques can be valuable when configured correctly.
Tip 9. Configure PHP Upload Limits and Execution Time
WordPress administrators sometimes need to upload large images, import databases, install plugins, or process backups.
PHP uses configuration directives to control resource consumption and upload behavior.
Several important settings include:
upload_max_filesize — Maximum size of an individual uploaded file.
post_max_size — Maximum size of an HTTP POST request body accepted by PHP.
max_execution_time — Maximum PHP script execution time, subject to platform-specific behavior.
memory_limit — Maximum memory a PHP script may allocate.
Some older WordPress tutorials recommend configuring these settings directly in .htaccess using php_value.
For example:
php_value upload_max_filesize 64M
php_value post_max_size 80M
php_value max_execution_time 120
php_value memory_limit 256M
These directives can work when PHP runs as an Apache module and the hosting configuration permits them.
However, many modern hosting environments use PHP-FPM or FastCGI instead of mod_php.
In those environments, adding php_value directives to .htaccess can cause an HTTP 500 Internal Server Error.
Therefore, do not copy these directives into your production .htaccess file without verifying your PHP execution mode.
For PHP-FPM environments, resource limits are usually configured through the hosting control panel, PHP-FPM pool configuration, or another supported PHP configuration mechanism.
Some environments support a .user.ini file for selected PHP settings.
An example .user.ini configuration is:
upload_max_filesize = 64M
post_max_size = 80M
max_execution_time = 120
memory_limit = 256M
The .user.ini file is separate from Apache .htaccess and is interpreted by supported PHP execution environments.
Changes may not take effect immediately because PHP can cache user-level configuration values.
Hosting providers may also enforce limits that cannot be overridden by individual website owners.
Increasing PHP resource limits does not automatically make a website faster. Excessively high values may increase memory consumption or allow inefficient scripts to consume more server resources.
Choose limits appropriate for the website’s real requirements.
For WordPress websites, also remember that WordPress has its own memory-related configuration options, which interact with the limits imposed by PHP and the hosting environment.
How to Test Your WordPress .htaccess Rules
After applying any of the preceding techniques, test the website carefully.
Start with the homepage, several posts, and the WordPress login page.
Check that CSS, JavaScript, images, and uploaded media continue loading correctly.
If you have installed a shopping cart, membership plugin, contact form, or other interactive feature, test those functions as well.
You can inspect server responses using curl.
For example:
curl -I https://example.com/
To check whether a protected file is accessible:
curl -I https://example.com/wp-config.php
A properly denied request will normally return HTTP 403 Forbidden, although the exact response may depend on additional server or CDN controls.
To inspect browser caching headers:
curl -I https://example.com/wp-content/uploads/example.jpg
Look for Cache-Control and Expires headers.
You can also use the browser’s Developer Tools Network panel to inspect response codes and resource-loading behavior.
If your website returns HTTP 500 after editing .htaccess, restore your backup and review the Apache error log.
A configuration error may result from unsupported directives, missing Apache modules, or incorrect syntax.
Apply one group of changes at a time instead of adding many unfamiliar rules simultaneously.
Additional WordPress Security Recommendations
Although .htaccess can provide useful protection, website security depends on several layers.
Keep WordPress core, themes, plugins, PHP, and the operating system updated to supported versions.
Remove unused plugins and themes that are no longer needed.
Protect administrator accounts with strong passwords and multifactor authentication.
Maintain reliable offsite backups and periodically test restoration procedures.
Use appropriate filesystem permissions and avoid making files or directories unnecessarily writable.
Consider a web application firewall to help detect common attacks against WordPress and its plugins.
Monitor access logs and error logs for suspicious activity.
If you use Cloudflare or another CDN, review its existing security and caching features before duplicating the same rules in Apache.
Finally, remember that .htaccess rules cannot repair insecure PHP code or vulnerable WordPress plugins.
Secure application development and proper maintenance remain essential.
Conclusion
The WordPress .htaccess file is a valuable configuration tool for websites running Apache HTTP Server.
In Part 1 of this series, we explored nine essential techniques covering permalink rewriting, login protection, IP address blocking, sensitive configuration files, upload directory security, internal PHP file protection, browser caching, and PHP resource limits.
Some techniques provide direct security benefits, while others improve website configuration and performance.
The most important principle is to understand what each directive does before adding it to a production website.
Modern Apache 2.4 and PHP-FPM environments differ significantly from older hosting configurations. Rules that worked years ago may now be obsolete, unnecessary, or incompatible.
A carefully maintained .htaccess file should contain only the directives required by your website.
In Part 2, we will explore more advanced configuration techniques, including caching headers, permanent redirects, sensitive PHP files, server signatures, timezone configuration, directory management, and script execution restrictions.
For more WordPress, Apache, PHP, Linux, and website administration tutorials, visit HostsDepot.com.
References
WordPress Developer Documentation — Hardening WordPress
https://developer.wordpress.org/advanced-administration/security/hardening/
Apache HTTP Server — .htaccess Files
https://httpd.apache.org/docs/2.4/howto/htaccess.html
Apache HTTP Server — Access Control
https://httpd.apache.org/docs/2.4/howto/access.html
Apache HTTP Server — mod_rewrite
https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html
Apache HTTP Server — mod_expires
https://httpd.apache.org/docs/2.4/mod/mod_expires.html
PHP Official Documentation — Configuration Changes
https://www.php.net/manual/en/configuration.changes.php
PHP Official Documentation — .user.ini Files
https://www.php.net/manual/en/configuration.file.per-user.php