12 Powerful .htaccess Tricks Every WordPress User Should Know

Your WordPress site‘s .htaccess file is like a secret control room that lets you fine-tune and supercharge your site‘s functionality. This humble configuration file powers everything from pretty permalinks to critical security features.

As a WordPress user, marketer, or site owner, having a few handy .htaccess tricks up your sleeve can be invaluable for protecting your site, boosting performance, and troubleshooting issues. That‘s why we‘ve compiled this ultimate guide to the 12 most useful .htaccess tricks that every WordPress user should know.

Before we dive in, always make a backup of your site and your original .htaccess file before making any changes. One typo or misplaced character could bring down your entire site, so it‘s crucial to have a restore point.

Also, some managed WordPress hosts don‘t allow .htaccess modifications, so check with your provider first. With that said, let‘s get started!

1. Lock down WordPress login pages

Here are two ways to harden your WordPress login security using .htaccess.

Password protect wp-admin

According to WordFence, brute force attacks on WordPress sites increased 400% in 2017 alone. Adding HTTP authentication to wp-admin creates another layer of defense:

<Files admin-ajax.php>
Order allow,deny
Allow from all 
Satisfy any
</Files>

AuthName "WordPress Admin"
AuthUserFile /path/to/.htpasswd
AuthType basic
Require valid-user

Generate the .htpasswd file using an online tool, then upload it to a directory that can‘t be publicly accessed. Now, accessing wp-admin will require this extra password.

Restrict wp-admin by IP

For even more security, you can restrict wp-admin access to specific IP addresses only:

<Limit GET POST>
order deny,allow
deny from all
allow from xx.xx.xx.xxx
allow from xx.xx.xx.xxy
</Limit>

Replace the placeholders with your authorized IP addresses. This is ideal if you have a static IP, like an office network.

2. Disable directory browsing

Directory browsing can expose the contents of unprotected directories, like images or ZIP files, to the public. To prevent this:

Options -Indexes

Simple but effective. Now, if a visitor lands on a directory URL without a default index file, they‘ll get a 403 forbidden error instead of a file listing.

3. Prevent PHP execution in untrusted folders

Even if you‘re careful about the files you upload to WordPress, a hacker could still find a way to sneak a malicious PHP script into your uploads directory. Disable PHP in uploads by creating an .htaccess file with:

<Files *.php>
deny from all
</Files>

As an alternative, you can whitelist PHP files, and block everything else:

<FilesMatch "\.(php|phtml)$">
Order Allow,Deny
Deny from All
</FilesMatch>

This way, you can control exactly which PHP files run.

4. Protect wp-config.php

Your wp-config.php file is like the "keys to the kingdom" – it contains your WordPress installation‘s database credentials and connection details. Safeguard it with:

<Files wp-config.php>
order allow,deny
deny from all
</Files>

For extra security, you can also move wp-config.php to a directory above your WordPress root. WordPress.org has a great guide on this.

5. Implement proper redirects

Whether you‘re restructuring permalinks or moving to a new domain, 301 redirects are essential for preserving hard-earned SEO. So instead of:

Redirect 301 /old-post/ http://example.com/new-post/ 

Use:

RedirectMatch 301 ^/old-post/$ http://example.com/new-post/

This matches the entire string, preventing potential redirect loops with similar URLs.

6. Block malicious bots and bad actors

Bots and hackers are always scanning for vulnerabilities or ways to exploit your WordPress site. Here are a few ways to stop them.

Ban suspicious IP addresses

If you‘re seeing a flood of malicious traffic from a specific IP, drop the banhammer with:

<Limit GET POST>
Order Allow,Deny
Allow from all
Deny from xx.xxx.xx.x
Deny from xx.xxx.xx.y 
</Limit>

Add a new "Deny from" line for each problematic IP address.

Stop image hotlinking

Hotlinking is when another site embeds your images on their pages, freeloading your bandwidth. To prevent it:

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

Replace "yourdomain" with your actual domain name. You can even redirect hotlinked images to an "Image theft hurts" graphic for a little public shaming.

Disable XML-RPC

XML-RPC is an old remote publishing protocol that‘s been largely replaced by the WordPress REST API. Unfortunately, it‘s been abused by hackers for brute force amplification attacks. Kinsta reports that up to 95% of all XML-RPC traffic is malicious.

If you don‘t need it, close the door on XML-RPC with:

<Files xmlrpc.php>
order deny,allow
deny from all
</Files>

You can also disable it via a plugin like Disable XML-RPC.

Put a stop to author scans

WordPress author pages (example.com/author/admin) can reveal usernames for hackers to target. Thwart reconnaissance with:

RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} author=\d
RewriteRule ^ /? [L,R=301]

Now, all author page requests will redirect to the homepage instead.

7. Strengthen .htaccess security

Since your .htaccess file can control so much of your WordPress site, you‘ll definitely want to lock it down:

<Files .htaccess>
order allow,deny
deny from all
</Files>

This denies access to your .htaccess file from all non-authorized users (i.e. anyone but you). Alternatively, you can move your .htaccess file to a directory above your site root, so it can‘t be accessed from the web at all.

8. Adjust PHP resource limits

By default, WordPress limits the maximum file upload size to 2MB. For larger files, you can increase it in .htaccess:

php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
php_value max_input_time 300

Adjust the numbers to fit your needs. Here‘s a quick reference table:

DirectiveDefaultSuggested
upload_max_filesize2M64M
post_max_size8M64M
max_execution_time30300
max_input_time60300

Keep in mind that your hosting environment and PHP configurations may set maximum limits.

9. Force HTTPS/SSL

If you‘ve installed an SSL certificate (and you really should), make sure visitors can‘t access your site over insecure HTTP. Add this to your .htaccess file:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]  

All HTTP traffic will get redirected to HTTPS. You can even take it a step further by enabling HTTP Strict Transport Security (HSTS).

10. Enable GZIP compression

GZIP compression drastically reduces the size of your pages and stylesheets before sending them to visitors. The result? Much faster load times.

According to HTTP Archive, 68% of websites use GZIP compression, and the 90th percentile site compresses 88% of their text content.

Here‘s how to implement GZIP in .htaccess:

<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>

Test thoroughly, as GZIP can occasionally cause issues with very old browsers. But performance-wise, it‘s a no-brainer.

11. Activate browser caching

Caching is another easy performance win you can activate via .htaccess. Just set some expiration times for different file types, so repeat visitors‘ browsers can load your assets locally instead of pulling from your server every time:

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>

Feel free to customize the time periods for each filetype as you see fit. Generally, static assets like images can be cached longer than frequently updated content types.

Using caching and GZIP together is a potent combo for slashing load times.

12. Optimize permalinks

Our final .htaccess trick is one you‘re probably already familiar with: pretty permalinks. WordPress uses the .htaccess file to transform ugly default URLs like http://yourdomain.com/?p=123 into clean, descriptive URLs like http://yourdomain.com/category/sample-post/.

Not only do pretty permalinks help SEO, but they‘re also more user-friendly and easier to remember. If you haven‘t updated your permalinks yet, go to Settings → Permalinks and select the "Post name" option.

WordPress will automatically add the required rewrite rules to your .htaccess file:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

You can usually leave these rules as-is. But if you run into any weird issues with your post pages, try replacing them with:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]
</IfModule>

This alternative syntax can fix problems with some WordPress plugins and themes.

Putting it all together

With these 12 essential .htaccess tricks in your WordPress toolbox, you‘ll be well on your way to a faster, safer, and more optimized WordPress site.

To sum up:

  1. Protect your login pages with extra passwords and IP allow lists.
  2. Turn off directory browsing to conceal sensitive files.
  3. Prevent unauthorized PHP execution in untrusted folders.
  4. Lock down wp-config.php and your .htaccess file itself.
  5. Use RedirectMatch for more precise 301 redirects.
  6. Block malicious bots, hackers, and hotlinkers with IP bans and rewrite rules.
  7. Disable XML-RPC if you‘re not using it.
  8. Increase WordPress‘s memory limit and max file size when necessary.
  9. Force SSL to keep your site secure.
  10. Activate GZIP compression for a big speed boost with little effort.
  11. Take advantage of browser caching for even more performance gains.
  12. Implement SEO-friendly permalinks.

But above all else, remember the "measure twice, cut once" strategy. Always test your .htaccess tweaks thoroughly, and keep a pristine original copy on hand in case you need to revert.

Think of .htaccess as a powerful sidekick that can help you fight off attackers, speed up your site, and smooth over any obstacles in your way. With a little know-how and a few strategic tricks, there‘s no limit to what you and .htaccess can accomplish together.

Now go forth and make your WordPress site the best it can be! If you get stuck, don‘t hesitate to reach out to your host‘s support team or your friendly neighborhood WordPress expert. You‘ve got this!

Did you like this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.