Ways to Improve Your WordPress Website’s Security And Speed Using .htaccess

improve-website-s-security-and-speed-using-htaccess

Have you ever thought if you can make your WordPress website faster and more secure without installing another plugin? If your website is hosted on an Apache server, the answer is yes.

The .htaccess file allows you to control important server-level settings that protect your website, improve loading speed and optimize how browsers handle your content. All it takes is a few carefully chosen rules that can mostly replace tasks that would otherwise need a whole bunch of plugins.

This guide walks you through some of the most useful .htaccess configurations for WordPress and explains how each one helps improve your website’s security and performance.

Best .htaccess Security Rules For WordPress 

1. Protect The .htaccess File

This rule blocks anyone from accessing the .htaccess file through a web browser. Since this file contains important website and security settings, it should never be publicly accessible.

Example

<Files .htaccess>

    Require all denied

</Files>

Website Impact

  • Prevents attackers from viewing your server configuration.
  • Protects rewrite rules and security settings.

2. Enforcing HTTPS With HSTS

This rule tells browsers to always use HTTPS when visiting your website. Once a visitor accesses your site over HTTPS, their browser will automatically use a secure connection for future visits, helping prevent insecure HTTP access.

Example

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

Website Impact

  • Prevents SSL stripping attacks.
  • Ensures encrypted connections.

3. WordPress Security Protection

These rules add an extra layer of security to your WordPress website by blocking user enumeration, protecting the login page, restricting access to sensitive WordPress files, and preventing automated comment spam.

Example

### For WordPress Only ###

#Block access to the REST API users endpoints in WordPress

RewriteCond %{REQUEST_METHOD} ^(GET|POST) [NC]

RewriteCond %{REQUEST_URI} ^(.*)wp-json/wp/v2/users [NC]

RewriteRule ^(.*)$ – [F]

#Require a secret key in the URL to access the login page in WordPress

#Example: ://yoursite.com

RewriteCond %{REQUEST_METHOD} GET

RewriteCond %{QUERY_STRING} !^you-own-unique-tocken=true$

RewriteCond %{REQUEST_URI} wp-login\.php [NC]

RewriteRule ^ – [F,L]

RewriteRule ^wp-admin/includes/ – [F,L]

RewriteRule !^wp-includes/ – [S=3]

RewriteRule ^wp-includes/[^/]+\.php$ – [F,L]

RewriteRule ^wp-includes/js/tinymce/langs/.+\.php – [F,L]

RewriteRule ^wp-includes/theme-compat/ – [F,L]

# Stop comment spammers who bypass the actual comment form

RewriteCond %{REQUEST_METHOD} POST

RewriteCond %{REQUEST_URI} .wp-comments-post\.php*

RewriteCond %{HTTP_REFERER} !.*yourdomain\.com.* [OR]

RewriteCond %{HTTP_USER_AGENT} ^$

RewriteRule .* – [F,L]

### WordPress Specific Code Ends ###

Website Impact

  • Blocks the WordPress REST API users endpoint to prevent user enumeration.
  • Protects the login page by requiring a secret URL parameter.
  • Prevents direct access to sensitive WordPress core files.
  • Stops bots from submitting spam comments directly.
  • Reduces the risk of brute-force attacks, information disclosure, and automated abuse while improving overall website security.

4. WordPress Login & XML-RPC Protection

This rule allows legitimate access to the WordPress login page while disabling the xmlrpc.php file, which is commonly targeted by brute-force attacks, DDoS attacks, and spam bots.

Example

### For WordPress Only ###

# Allow AJAX requests to bypass the login prompt

<FilesMatch “^(wp-login\.php)$”>

    Order Allow,Deny

    Allow from all

    Satisfy Any

</FilesMatch>

# Disable XML-RPC

<Files xmlrpc.php>

    Require all denied

</Files>

Website Impact

  • Ensures the WordPress login page works correctly.
  • Blocks access to the vulnerable xmlrpc.php endpoint.
  • Reduces brute-force attacks, spam, and abuse.
  • Improves the overall security of your WordPress website.

5. Blocking Malicious User Agents

This rule blocks requests from known security scanners, penetration testing tools, and suspicious user agents. It also rejects requests containing malicious characters in the User-Agent header.

Example 

# Block known malicious/scanner user agents

RewriteCond %{HTTP_USER_AGENT} (havij|nikto|sqlmap|nmap|acunetix|nessus|w3af|dirbuster) [NC,OR]

RewriteCond %{HTTP_USER_AGENT} (<|>|’|%0A|%0D|%27|%3C|%3E|%00) [NC]

RewriteRule .* – [F,L]

Impact

  • Blocks common automated scanning tools and bots.
  • Reduces unwanted probing and malicious requests.
  • Helps protect the website from reconnaissance and automated attacks.
  • Improves overall website security with minimal impact on legitimate visitors.

6. Add HTTP Security Headers

Security headers instruct browsers to protect users against common attacks.

Example

<IfModule mod_headers.c>

Header always set X-Frame-Options “SAMEORIGIN”

Header always set X-Content-Type-Options “nosniff”

Header always set Referrer-Policy “strict-origin-when-cross-origin”

Header always set Permissions-Policy “geolocation=(), camera=(), microphone=()”

</IfModule>

Website Impact

  • Prevents clickjacking.
  • Blocks MIME sniffing.
  • Improves browser security.
  • Protects user privacy.

7. Configuring a Content Security Policy (CSP)

This rule defines a Content Security Policy (CSP), which controls the sources from which your website can load scripts, styles, images, fonts, and other resources. It helps prevent attacks such as Cross-Site Scripting (XSS), code injection, and mixed-content issues by allowing content only from trusted sources.

Example

    # Content Security Policy

    #Header set Content-Security-Policy -Report-Only

    Header set Content-Security-Policy “default-src ‘none’; \

    script-src ‘self’ ‘unsafe-inline’ ‘unsafe-eval’ ; \

    style-src ‘self’ ‘unsafe-inline’ ; \

    font-src ‘self’ ; \

    img-src ‘self’ ; \

    connect-src ‘self’ ; \

    frame-src ‘self’ ; \

    frame-ancestors ‘self’; \

    object-src ‘self’; \

    base-uri ‘self’; \

    block-all-mixed-content; \

    upgrade-insecure-requests; \

    media-src ‘self’ blob:; \

    form-action ‘self’; \

    worker-src blob:;”

Website Impact

  • Protects against XSS and code injection attacks.
  • Allows resources to load only from trusted sources.
  • Forces secure HTTPS content and blocks mixed content.
  • Improves website security while giving you full control over resource loading.

Best .htaccess Performance Optimizations For WordPress 

1. Setting PHP Upload And Execution Limits

These settings define the maximum upload size, memory usage, and script execution time for your PHP application. They help prevent server overload while ensuring your website runs smoothly.

Example

# Upload and execution limits

php_value upload_max_filesize 10M

php_value post_max_size 12M

php_value max_execution_time 60

php_value max_input_time 60

php_value memory_limit 128M

Website Impact

  • Controls the maximum file upload size.
  • Prevents long-running scripts from consuming server resources.
  • Limits PHP memory usage for better server stability.
  • Improves website performance, reliability, and security.

2. Skipping Compression For Already-Compressed Files

This rule prevents Gzip compression from being applied to files that are already compressed, such as images and archive files. Compressing these files again provides little or no benefit and can waste server resources

Example

# Skip already-compressed binary formats

SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|webp|zip|gz|bz2|rar|7z)$ no-gzip

Website Impact

  • Reduces unnecessary server processing.
  • Saves CPU resources and improves server efficiency.
  • Helps maintain faster website performance.

3. Configuring Browser Cache Expiration

This rule sets expiration times for different types of website files. Browsers store these files locally for a specified period, so they don’t need to be downloaded again on every visit. Static files like images are cached longer, while frequently updated files like HTML are refreshed more often.

Example

## EXPIRES CACHING ##

<IfModule mod_expires.c>

ExpiresActive On

ExpiresByType image/jpg “access plus 1 year”

ExpiresByType image/jpeg “access plus 1 year”

ExpiresByType image/gif “access plus 1 year”

ExpiresByType image/png “access plus 1 year”

ExpiresByType text/css “access plus 1 month”

ExpiresByType text/html “access plus 0 seconds”

ExpiresByType application/pdf “access plus 1 month”

ExpiresByType application/javascript    “access plus 1 week”

ExpiresByType text/x-javascript “access plus 1 month”

ExpiresByType application/x-shockwave-flash “access plus 1 month”

ExpiresByType image/x-icon “access plus 1 year”

 ExpiresByType image/vnd.microsoft.icon  “access plus 1 year”

ExpiresDefault “access plus 1 month”

Website Impact

  • Speeds up page loading for returning visitors.
  • Reduces server load and bandwidth usage.
  • Improves browser caching for images, CSS, JavaScript, PDFs, and icons.
  • Enhances website performance, Core Web Vitals, and SEO.

4. Optimizing Browser Caching And File Compression

This configuration improves your website’s performance by setting the correct MIME types, enabling browser caching, and compressing website files before they are sent to visitors. Together, these optimizations reduce page load times and improve the overall browsing experience.

Example

# W3TC Browser Cache

<IfModule mod_mime.c>

    AddType …

</IfModule>

<IfModule mod_expires.c>

    ExpiresActive On

    ExpiresByType …

</IfModule>

<IfModule mod_deflate.c>

    AddOutputFilterByType DEFLATE …

</IfModule>

Website Impact

  • Loads web pages faster by compressing files before delivery.
  • Enables browser caching so visitors don’t download the same files repeatedly.
  • Reduces server bandwidth usage and improves server performance.

5. Browser Compatibility For Compression

This rule ensures Gzip compression works correctly with older browsers that have known compatibility issues. It also adds the Vary: User-Agent header so caches store the correct version of compressed content for different browsers.

Example

# Remove browser bugs (only needed for really old browsers)

BrowserMatch ^Mozilla/4 gzip-only-text/html

BrowserMatch ^Mozilla/4\.0[678] no-gzip

BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

Header append Vary User-Agent

Website Impact

  • Improves compatibility with older browsers.
  • Prevents caching issues by varying content based on the browser.
  • Enhances website performance without affecting modern browsers.

Things To Keep In Mind Before Editing .htaccess 

Before editing your .htaccess file:

  • Always back up your existing .htaccess file.
  • Add one rule at a time instead of making multiple changes at once.
  • Test your website after each rule to ensure it works correctly.
  • If you encounter a 500 Internal Server Error, restore your backup immediately and review the last rule you added.

Conclusion

Optimizing your WordPress website with .htaccess is an effective way to improve security and performance without multiple plugins sitting around. 

Using these server-level configurations, you can lower your page load times, strengthen security and offer a faster & more reliable experience for your visitors.

Just remember to always have a backup of your existing .htaccess file before making changes. Apply one rule at a time, and test your website thoroughly to make sure everything works as expected.

If you need professional help implementing advanced WordPress security, performance optimizations, or custom development, consider working with an experienced WordPress development company like Innoway Technology, which has over 10 years of experience building secure, high performing WordPress websites and custom web solutions.

Related Articles: