21 Most Useful .htaccess Tricks to Secure, Optimize and Improve User Experience on WordPress Sites

.htaccess is one of the most critical files in WordPress. It takes responsibility for defining rules for your server to follow as well as controlling all files and folders of your website.

Apart from that, .htaccess also performs a central role in improving WordPress security and performance.

In this article, we will amaze you by presenting the 21 most useful .htaccess tricks to secure, optimize WordPress, as well as improving user experience on WordPress sites.

Before revealing the top 21 .htaccess tricks, let us walk you through what you need to know about the .htaccess file.

Getting Ready

.htaccess is a configuration file of Apache which is used to implement changes in functions and features of the server. The word .htaccess is short for “hypertext access.”

The .htaccess file is located in the root folder of your WordPress site.

htaccess file

Normally, the files whose names start with a dot are hidden files, which means they’re not visible by default. In case you can’t see the .htaccess file, turn on  “Show Hidden Files” in your FTP client or File Manager.

show hidden files

What if you don’t have the .htaccess file in the root folder of your WordPress site? You need to create one. Don’t worry, it’s as easy as pie! What you need to do is:

  • First, create a new text file on your computer and save it as .htaccess.
  • Copy and paste the following codes in that file.
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
  • Upload that file to the root folder of your site using your File Manager.
  • Lastly, you need to upload that .htaccess file to this folder: …/home/yourweb/public_html/.htaccess.

The .htaccess file is such a powerful yet dangerous file to modify, especially if you have little knowledge about how the .htaccess works. As a small coding mistake can cause internal server errors, you need to back up your existing .htaccess file and save it to your desktop beforehand. In case anything goes wrong, you can use the backup file.

And one more thing, just do one trick at a time. After you apply one trick, it’s necessary to go back to your WordPress site and check if it functions properly.

Since we’ve learned about the WordPress .htaccess file, it’s time to leak out the top 21 useful .htaccess tricks for WordPress. We will make it as straightforward as possible. These tricks will be categorized into 3 groups:

10 Most Useful .htaccess Tricks to Tighten WordPress Security

WordPress security is always a prime concern. We will show you the 10 most useful .htaccess tricks to add additional protection layers to your WordPress admin area, folders, and plugin files.

Protect Your WordPress Admin Area

You can protect your WordPress admin area by using .htaccess to limit IP access to wp-admin. The wp-admin directory contains all the files required to run the WordPress dashboard.

It includes administrative functions, such as installing themes, using plugins or writing posts, etc. Allowing only selected IP addresses access to the wp-admin directory helps protect your WordPress site from hackers.

To limit IP access to the admin area, copy and paste the following code snippet to your .htaccess file.

AuthUserFile /dev/null
AuthGroupFile /dev/null
AuthName "WordPress Admin Access Control"
AuthType Basic
<LIMIT GET>
order deny,allow
deny from all
# whitelist User1's IP address
allow from xx.xx.xx.xxx
# whitelist User2's IP address
allow from
# whitelist User3's IP address
allow from xx.xx.xx.xxx
# whitelist User4's IP address
allow from xx.xx.xx.xxx
# whitelist User5 IP address
allow from xx.xx.xx.xxx
</LIMIT>

In the codes above, “User1,” “User2,” “User3,” etc are the IPs you allow access to wp-admin. They can be admins, editors, contributors, or visitors. Don’t forget to replace the “xx.xx.xx.xxx” with your IP or their IPs.

Add Password Protection to Your Directories

You can use the .htaccess file to add an additional password protection to your WordPress directory.

What you need to do is:

  • Create a .htpasswd file by using htpasswd-generator.
  • Upload that .htpasswd file to your WordPress wp-admin folder.
  • Create a .htaccess file and upload it in the wp-admin directory.
  • Add the following code to your .htaccess file.
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /home/public_html/wp-admin/.htpasswd
require valid-user

Make sure that you replace “AuthUserFile” with your .htpasswds file.

Disable Directory Browsing

Apache web server allows directory browsing. This means that all the files and folders in the root of the web server are listed and accessible to any visitors. Disable directory browsing is highly recommended as it prevents hackers from getting into your directory and file structure to find a vulnerable file.

To disable directory browsing in WordPress, all you need to do is insert the following line in the .htaccess file:

Options -Indexes

Disable PHP Execution in Certain Folders

Commonly, hackers upload backdoor files to the wp-includes or wp-content/uploads folders to run the PHP files, which aims to damage your site.

To disable PHP execution using the .htaccess file, you need to:

  • Create a blank .htaccess file.
  • Save the file and upload it to wp-includes and wp-content/upload folders.
  • Add the following codes to the file:
<Files *.php>
deny from all
</Files>

Secure wp-config.php File

wp-config.php is one of the most important files as it contains the database name, access credentials, and other crucial data.

To secure the wp-config.php file, you can add the following codes to the .htaccess file. This helps to deny access to the wp-config.php file.

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

Ban Suspicious IP Addresses

You can easily block certain IP access to your site by adding the code lines below to your .htaccess file:

order allow, deny
deny from xx.xx.xx.xxx
allow from all

Don’t forget to change “xx.xx.xx.xxx” to the IP addresses you want to restrict access to.

Protect .htaccess Unauthorized Access

So far, you’ve seen how useful the .htaccess file is. Your website would be at risk if this file is accessed by hackers. Copying and pasting the following codes to your .htaccess file will help protect it from unauthorized access:

<files ~ "^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</files>

This code snippet restricts access to all files beginning with “Hh,” “Tt,” “Aa,” including your .htaccess file.

Disable XML-RPC Access

By default, the XML-RPC file is installed on every WordPress site. This file enables your website to utilize third-party plugins, which outside users often take advantage of to infiltrate your site. If you’re not using any third-party apps, you should disable this feature.

There are many ways to disable the XML-RPC file, one of which is inserting the following codes in your .htaccess file:

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

Secure WordPress Plugin Files

As we mentioned above, plugins are incredibly useful to you yet can be a loophole for attackers to exploit. To prevent others from having direct access to your plugin files, copy and paste four code lines below to your .htaccess file:

<files ~ ".(js|css)$"="&”.(js|css)$&">
order allow,deny
allow from all
</files>

Disable Author Scanning in WordPress

Author scanning is a common technique used in brute force attacks. Hackers scan your website and try to get the author ID. Next, they crack the password by trying different password combinations and then gain access to your WordPress administration.

The easiest way to block author scanning in WordPress is through the .htaccess file.

By adding the following codes to your .htaccess file, you can keep the author ID secret and save your site from brute force attacks.

# BEGIN block author scans
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} (author=\d+) [NC]
RewriteRule .* - [F]
# END block author scans

The code snippet above will block bots from running author scans while your users can still access the author pages.

We’ve shown you the most useful .htaccess tricks to secure WordPress. Now let’s discover how to optimize your WordPress site with the .htaccess file.

9 Clever .htaccess Tricks to Optimize WordPress

Do you know .htaccess is a contributing factor in your WordPress optimization?

By playing some tricks in your .htaccess file, you can speed your site up and increase organic search visibility.

Seems pigs can fly? The 9 following tricks will blow your mind!

Enable Browser Caching

Browser caching, once enabled, will allow visitors to save images from your web page. As such, they won’t have to download the same data again when revisiting the same site. This contributes to speeding up your site.

To enable browser caching, all you need to do is add these lines of code to your .htaccess file:

## EXPIRES CACHING ##
<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>
## EXPIRES CACHING ##

Set Up 301 Redirects

Setting up 301 redirects in your .htaccess file will let the search engine and your users know that the old page or link has been replaced by a new one. This method is highly recommended to direct traffic from an existing page.

Instead of showing an error page, inserting the following code lines to your .htaccess file and it will show a new page.

Redirect 301 /oldurl/ http://www.example.com/newurl
Redirect 301 /category/television/ http://www.example.com/category/tv/

Correct URL Typo Automatically

This trick will enable users who misspell your URL to be still able to access your pages. By inserting the following code snippet into your .htaccess file, you’ve created a Check Spelling directive which helps to correct typos and navigate to correct documents.

<ifmodule mod_speling.c>
CheckSpelling On
</ifmodule>

Note: The codes above work extremely well for small mistakes but not gross typing errors.

Add a Slash to the End of URLs

URLs with a trailing slash like this “example.com/abc/” indicates a directory. URLs without a trailing slash, like “example.com/abc”, usually denotes a file. In other words, 2 URLs looking alike can deliver different content and produce totally different experiences. This can cause horrible confusion to your users and search engines. Plus, your website may run into duplicate content issues if the URLs on your site aren’t consistent.

Adding the codes below to your .htaccess file can help standardize your URLs, which will force all of your pages to end with a slash.

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !#
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://domain.com/$1/ [L,R=301]

Customize Permalinks for Better URLs

One of the best uses of .htaccess file is you can edit it to customize permalinks for SEO-friendly URLs. By adding some codes, you can replace boring strings of symbols and numbers with your relevant keywords. This enables you to create a cleaner URL for high organic search visibility.

Here is the codes to customize permalinks using .htaccess file:

# BEGIN WordPress
<ifmodule mod_rewrite.c="mod_rewrite.c">
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</ifmodule>
# END WordPress

Redirect WWW to Non-WWW and Vice Versa

Do you know that there are two versions of your WordPress domain, “www” and “non-www” ? You should choose only one and stick with it to avoid the possibility of duplicate content.

If you want to use “non-www,” you need to redirect “www” to “non-www” by adding the following codes to your .htaccess file.

RewriteEngine On
RewriteCond %{HTTP_HOST} !^your-domain.com$ [NC] RewriteRule ^(.*)$ http://your-domain.com/$1 [R=301,L]

In case you want to use “www,” insert the following codes to your .htaccess file to redirect “non-www” to “www”:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Make sure to change “your-domain.com” to your site.

Disable Image Hotlinking

An issue with image hotlinking is a bandwidth problem. If an image is hotlinked into a website, that website doesn’t use any of its bandwidth to host that image. Instead, every time someone views that image, the bandwidth of the original website will be eaten into. This isn’t a big problem for small websites. However, if you run a website containing lots of images, it’s a serious concern as it’ll severely slow down your site.

To ensure other websites can’t hotlink to your images, add the following code snippet to your .htaccess file:

RewriteEngine on RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?your-site.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www.)?your-other-domain.com [NC]
RewriteRule .(jpg|jpeg|png|gif)$ http://i.imgur.com/g7ptdBB.png [NC,R,L]

Make sure that you change “your-site.com” to your website and replace “your-other-domain.com” with the website you allow image hotlinking.

Enable Gzip Compression

Gzip is a compressed method for faster transfers. By being able to deflate most of the file types, Gzip compression allows your server to provide smaller file sizes, leading to a faster web loading process.

To enable the Gzip compression, adding a few lines of code below to your .htaccess file:

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

After that, don’t forget to save your .htaccess file and refresh your WordPress site.

Increase PHP File Upload Size

Commonly, WordPress will send you messages of “exceeds the maximum upload size for this site” or “warning post content-length of bytes exceeds the limit” whenever you want to upload a larger file.

You can tell your web server to increase file upload size with the following codes implemented on to your .htaccess file:

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

Apart from protecting and optimizing your WordPress, we can make use of the .htaccess file to improve user experience. Check out the next part for instructions!

2 Helpful .htaccess Tricks to Improve User Experiences

In this part, we’ll be sharing with you 2 cool tricks to turn some dull error pages and website maintenance messages into vividly custom and helpful ones. This not only helps to improve user experience but also retain visitor engagement to your site. Let’s dive in!

Create Custom Error Pages

Commonly, errors like 403, 404, and 500 show up when users try to access non-existent pages. While running into error messages can cause a frustrating experience for visitors, we can improve it by creating user-friendly custom error pages.

But how to add your own custom error pages to your site and serve them to your visitors?

Using this .htaccess trick, of course!

  • First, you need to create an error page and upload it to your base WordPress installation directory.
  • Then add the following code snippet to your .htaccess file to enable the custom error page:
# custom error pages
ErrorDocument 401 /err/401.php
ErrorDocument 403 /err/403.php
ErrorDocument 404 /err/404.php
ErrorDocument 500 /err/500.php

Redirect Visitor to Maintenance Page

You should forward visitors to an automatic maintenance message if your site is performing an upgrade or undergoing maintenance operation.

To create a redirect message for maintenance, you first have to create a file named maintenance.html in your web directory.

Then you can use the .htaccess file to accomplish this, using the following codes:

RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.html$
RewriteCond %{REMOTE_ADDR} !^123\.123\.123\.123
RewriteRule $ /maintenance.html [R=302,L]

You only need to change the URL in bold to whatever page you’d like to display. You can delete it once the maintenance operation is over.

Conclusion

We’ve guided you through the top 21 .htaccess tricks you might need for your WordPress site.

With the 21 coolest .htaccess tricks we’ve provided today, you can consider to use them to strengthen your WordPress security, optimize it, and improve user experience.

And do not take any chance with the .htaccess file. As a single error can break your site, it’s important to back up your .htaccess file beforehand and keep track of all of your changes.

How many of these tricks have you tried? Do you have any other .htaccess tips that you would like to recommend to us?

Leave a Reply

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