The Ultimate Guide to .htaccess File in WordPress

The Ultimate Guide to .htaccess File in WordPress

Did you know that the sites having WordPress CMS contain  .htaccess file? Indeed, WordPress automatically created during installation to include the setting permalinks of the site.

When you go to Settings >> Permalinks to choose a URL format, the .htaccess file is modified. Still, you must know that this file may play a much larger role. The .htaccess file is an Apache configuration file, the software used by your server to function.

The contents of this file will give directions to Apache for the server to behave in a certain way.

With the .htaccess file we will be including:

  • Improve site security
  • Increase the speed of loading
  • Set up redirects
  • Limit spam
  • And even make small jokes 🙂

Are you interested is not it? So continue reading, you will not be dissatisfied!

Before starting

Before diving into the thick of it, we will discuss the basics so that beginners are not dropped from the beginning of the article 😉

Operation .htaccess files

The latest information you need to know is that a site can have multiple files of .htaccess

First of all, .htaccess located at the root of the site. The root of a site is where all the files of WordPress such as wp-admin folders, wp-includes, and wp-content plus some other files included.

The changes done in .htaccess file will affect the entire site.

.htaccess can influence the directories in which they are located and in their sub-directories too.

Caution while editing code in .htaccess

If we imagine that a .htaccess is present in the wp-content/uploads directory uploads and all sub-directories will be impacted by what is defined in the .htaccess

Above all, take your own!

Customizing the code in .htaccess is pretty simple (especially with the pieces of code that offer the rest of this article 😉)

Before making any changes, back up the original contents of your .htaccess file. To do this, you can:

  • Copy your old/current file & save it to your local PC
  • Copy your old/current file & rename with .htaccess-old on your server.

In the matter, you can quickly restore the original content.

To make changes, follow these steps:

  • Open the file in your code editor
  • Place your additions code in the file
  • Save all
  • Update website to see if all is well

Updating your website is very important because we must be confident that the added code is not a problem.

In general, a 500 error “Internal Server Error” will appear on the screen in case of mistakes:

In this case, cancel your changes and save again and everything should be back to normal.

Sometimes it happens that some hosts do not accept the code in the.htaccess

We must contact support for your host for more information. With any luck, there needs only a slight change for it to work.

How to create a .htaccess file?

Logically, your site should have at least one .htaccess file, the one at the root of your site. You can change it with your code editor.

There are other solutions like the plugin WP .htaccess Editor or Yoast to edit directly from WordPress but there is a problem it will go through the FTP and your code editor, so you better make directly.

If you need to add a file .htaccess in a subdirectory, do the following:

How to create .htaccess on the computer?

  • Create a new text file and save as with .htaccess
  • Edit it to your liking
  • Send it to the root of your server

How to create .htaccess directly on the server?

  • Right-click in the folder you need to create
  • Add a new file and name “.htaccess
  • Edit it with your code editor

Comments in .htaccess

As with all computer languages, the file .htaccess allows you to include comments. In our case, just place the symbol # at the beginning of the line for it to be ignored. This is useful to remember that realize lines of code.

You will have the opportunity to see comments in the examples in this article. We can begin to get into the thick of it with the file.

# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress

Code of default WordPress

If you use WordPress Multisite mode, the default file will be different. This does not affect you in most cases.

Now that you have located the file, you will be able to enrich its content with the codes below to get specific things. This may relate to security, but also other things.

Do not include code between the comments  # BEGIN WordPress and  # END WordPress because it is possible that the code is amended in some cases.

Warning: Make a backup of your file .htaccess of origin before making any changes. You need to go back in case of problems!

How to disable directory listing in .htaccess?

By default, if you try to access directories of a site, the server will display. The layout will look like:

You can imagine that this is a godsend for hackers. The fact that they can see the files on your site will help them better able to attack. Insert the following code in your file .htaccess to protect your site:

# Disable the display of directory content
Options All -Indexes

It is also possible to use this code to prevent directory listings:

# Alternative to prevent directory listing
IndexIgnore *

How to hide server information in .htaccess?

Some hosts, the displayed page may contain information about the server. This information can provide information to potential attackers.
It is better to hide with the following code:

# Hide server information
ServerSignature Off

How to set encoding of the default character in .htaccess?

The following code defines the character encoding text files and HTML as UTF-8. Without this, there are risks that accents are not well considered.

# Default encoding of text and HTML files
AddCharset UTF-8 .html

How to protect the wp-config.php with .htaccess?

The web configuration file (wp-config.php) contains the password to connect to the database. This is the most sensitive file from your site. It is the potential attacker’s target. It is possible to protect it by adding code to the file .htaccess main:

# Protect wp-config.php file
order allow,deny
deny from all

Protect the .htaccess file itself

Like the wp-config.php file, the file .htaccess must be protected to the maximum. To do this, insert this code:

# Protect .htaccess and .htpasswds files
order allow, deny
deny from all
satisfy all

How to avoid spam comments in .htaccess?

You know as much as me if you have a blog comment spam is a real wound. Fortunately, there is a trick to protect them directly in the file .htaccess. This is not a quick fix but combined with the Akismet plugin, the majority of spam should be filtered.

# Avoid comments spam
RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
RewriteCond %{HTTP_REFERER} !* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]

Remember to replace your domain name.

How to disable hotlinking of your images in .htaccess?

And yes, a new Anglicism appeared on Startwithclick. Rest assured, I will explain everything. In fact, once you add images to your site (for example in an article), anyone can copy the URL of your pictures and display it on its website.

One might say that this is not so bad but if for some reason X or Y followed a site takes your image and displays it on one of its pages, queries will be performed at the server.

The hotlinking is a bandwidth theft. If your site is installed on a small shared hosting, your web host may not appreciate because resources are limited.

To avoid the problem, insert and customize this code in your file .htaccess:

# Disable hotlinking of your images
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)? [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ [NC,R,L]

Replace with your domain name

To allow certain sites to display your images, use the following code:

# Allow hotlinking of your images
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)? [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)? [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)? [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ [NC,R,L]

Replace,, with your domain name

You can also customize the picture to be displayed instead of the requested image. I added something simple, but you can be more playful😉

How to block IP addresses in .htaccess?

If you see particular IP trying to connect too often the administration of your site, you can get rid of blocking their IP address. You also have the ability to recover the IP addresses of spammers comments to ban your site. This solution is not final because your assailant may change IP address but will work for the least talented people.

# Block IP address
order allow, deny
deny from
allow from all

Replace with the IP address to be banned

How to block visitors from some sites?

If you realize that a site is not by a link to you and you do not want visitors to this site have access to your site, use this code:

# Prevent visitors from the following site
RewriteEngine on
RewriteCond %{HTTP_REFERER} [NC,OR]
RewriteCond %{HTTP_REFERER} [NC,OR]
RewriteRule .* - [F]

Replace and by the sites of your choice

Redirect visitors from one site to another

To go further than the previous tip, you can divert visitors from individual sites to another site. Both say that there is something good laugh. Here’s the code to use:

# Redirect visitors coming to another site
RewriteEngine on
RewriteCond %{HTTP_REFERER} sitesource\.com/
RewriteRule ^(.*)$ [R=301,L]

Replace the source site and destination of your choice by those

Create redirects

.htaccess allows you to make referrals. This is handy to redirect some pages, but if you want to create a lot of referrals, I recommend the WordPress Redirection plugin.

Here is how to create still redirects to the file .htaccess:

# Redirect any page
Redirect 301 /seo/
# Redirection of a new category
Redirect 301 /category/seo/

Redirect the address without www to www

When you put up a site, one of the actions to accomplish priority is to redirect the site without the www to the version with www (or the reverse).

If you do the test the next time you create a site, you will find that the two addresses do not necessarily return to your site.

In some cases, the host does this automatically, or it must be activated via the administration of the host.

If you need to perform this redirection manually, use the following code replacing your site:

# Redirection du site sans www vers www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^ [NC]
RewriteRule ^(.*)$  [L,R=301]

Replace with your domain name

Redirect www to non-www

Conversely, if you do not want the www before the name of your site, it is possible to make a redirect to the version without www.

Insert the following code in the file .htaccess:

# Redirecting the site with www to the version without www
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.site\.com [NC]
RewriteRule ^(.*)$  [L,R=301]

Replace with your domain name

Caution: Do not use this code with the previous code otherwise your site will suffer a redirect loop (non-www redirect to the www version & that will redirect to non-www, etc.)

Redirect to HTTPS

If you set up an SSL certificate on your site to switch to HTTPS, you must be sure that all your visitors navigate well on the secure version of your site.

Otherwise, sensitive information could be retrieved by hackers (personal or bank details, for example). Use the following code to move your entire site to HTTPS:

# Redirection to HTTPS 
RewriteCond     %{SERVER_PORT} ^80$
RewriteRule     ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]

Force download specific files

When one wishes to download a file from a site, sometimes our browser tries to open it for viewing. Personally, I find it convenient to PDF files, on the other hand, it is very unpleasant for other file types. Insert the following code to your visitors directly download files with these extensions (edit them on your own):

# Force download for these file types
AddType application/octet-stream .doc .docx .xls .xlsx .csv .mp3 .mp4

Create a custom maintenance page

There are cases where the maintenace page can not be displayed. While updating WordPress or the plugin, if an error occurs, maintenance page will not be displayed. It’s annoying, Isn’t? To get free from a maintenance page issue, you can use the following code:

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

For this to work, you must:

  • Create maintenance.html file with content that the site is down for maintenance
  • Add your IP address in line 4 (keeping “\”) to allow you to access the site.

When maintenance is completed, put the “#” in front of each line to make them comment.

Enable caching

The file .htaccess allows you to cache certain file on your site your visitor’s browser loading is faster. Indeed, the browser will not need to re-download the files in its cache. To do this, insert the following code:

# caching files in the browser
ExpiresActive On
ExpiresDefault "access plus 1 month"
ExpiresByType text/html "access plus 0 seconds"
ExpiresByType text/xml "access plus 0 seconds"
ExpiresByType application/xml "access plus 0 seconds"
ExpiresByType application/json "access plus 0 seconds"
ExpiresByType application/pdf "access plus 0 seconds"
ExpiresByType application/rss+xml "access plus 1 hour"
ExpiresByType application/atom+xml "access plus 1 hour"
ExpiresByType application/x-font-ttf "access plus 1 month"
ExpiresByType font/opentype "access plus 1 month"
ExpiresByType application/x-font-woff "access plus 1 month"
ExpiresByType application/x-font-woff2 "access plus 1 month"
ExpiresByType image/svg+xml "access plus 1 month"
ExpiresByType application/ "access plus 1 month"
ExpiresByType image/jpg "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType video/ogg "access plus 1 month"
ExpiresByType audio/ogg "access plus 1 month"
ExpiresByType video/mp4 "access plus 1 month"
ExpiresByType video/webm "access plus 1 month"
ExpiresByType text/css "access plus 6 month"
ExpiresByType application/javascript "access plus 6 month"
ExpiresByType application/x-shockwave-flash "access plus 1 week"
ExpiresByType image/x-icon "access plus 1 week"
# Header
Header unset ETag
FileETag None
<filesMatch "\.(ico|jpe?g|png|gif|swf)$">  
Header set Cache-Control "public"  
<filesMatch "\.(css)$">  
Header set Cache-Control "public"  
<filesMatch "\.(js)$">  
Header set Cache-Control "private"  
<filesMatch "\.(x?html?|php)$">  
Header set Cache-Control "private, must-revalidate"

The file cache setting will be valid for the period specified for each type of file or until the empty visitor’s cache.

Enable Compression

In addition to everything we have seen so far, it is possible to compress some resources before they are transferred from the server to the browser.

And who says file compression said faster frame rate for the page. I recommend you implement this code to give a boost to your site:

# Static File Compression
AddOutputFilterByType DEFLATE text/xhtml text/html text/plain text/xml text/javascript application/x-javascript text/css 
BrowserMatch ^Mozilla/4 gzip-only-text/html 
BrowserMatch ^Mozilla/4\.0[678] no-gzip 
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html 
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary 
Header append Vary User-Agent env=!dont-vary 
AddOutputFilterByType DEFLATE text/html  
AddOutputFilterByType DEFLATE text/plain  
AddOutputFilterByType DEFLATE text/xml  
AddOutputFilterByType DEFLATE text/css  
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE font/opentype
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/json

Disable access to individual scripts

To operate, WordPress uses scripts in the directory wp-includes; however, there is no reason to access it directly. Use this code to limit access:

# Block the use of certain scripts
RewriteEngine On
RewriteBase /
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]

Protection against file injections

Hackers may attempt to send files to your server to take control of your site. To put their sticks in the wheels, you can include this code in your file .htaccess:

# Protection against injections of files
RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=http:// [OR]
RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=(\.\.//?)+ [OR]
RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=/([a-z0-9_.]//?)+ [NC]

RewriteRule .* – [F]

Protection against other threats

On Facebook, one of my friends told me that it was possible to guard the “clickjacking” and other threats by adding a few lines in the file .htaccess.

FYI, clickjacking is a technique used to convince a visitor that is on your site then this is not the case with tags frame or iframe.

The following code allows you to protect against clickjacking, fight against other threats such as MIME Sniffing and block content in an XSS attack.

# Protections diverses (XSS, clickjacking et MIME-Type sniffing)
Header set X-XSS-Protection "1; mode=block"
Header always append X-Frame-Options SAMEORIGIN
Header set X-Content-Type-Options: "nosniff”

.htaccess in wp-admin

Wp-Admin This is the lair of your site. The place where you are going to write articles, configure your menus, set your theme and much more.

It goes without saying that unauthorized persons may enter the sanctuary. Otherwise, beware damage. Here it is possible to harden security through a .htaccess you have placed in the folder wp-admin of your site.

Limit access to site administration

Only persons with the listed IP can access the folder wp-admin. Rather convenient to prevent foreign connect to your website (even if they have the right password).

order deny,allow
deny from all
# IP d'Alex
allow from
# IP de Nico
allow from
# IP d'un autre point d'accès
allow from

.htaccess in wp-includes

Block direct access to PHP files. Create a file .htaccessin wp-includes and paste the following code to prevent PHP files are loaded directly:

# Block direct access to PHP files (Thanks to Sucuri)
allow from all
<FilesMatch "\.(?i:php)$">
Order allow,deny
Deny from all
Require all denied
Allow from all
Allow from all

Sucuri plugin provides the above code. Also, I suggest you subscribe to their service to sleep soundly at safety.

.htaccess in wp-content

Block direct access to PHP files. For the record wp-content, the code is similar; there are just exceptions within:

# Block direct access to PHP files (Thanks to Sucuri)
<FilesMatch "\.(?i:php)$">
Order allow,deny
Deny from all
Require all denied  

.htaccess in wp-content / uploads

Block direct access to PHP files. Always with this code, protect the folder where the media are stored to prevent PHP files are executed by someone from outside (for example- an evil hacker ).

# Block direct access to PHP files (Thanks to Sucuri) 
<FilesMatch "\.(?i:php)$">
Order allow,deny
Deny from all
Require all denied

Conclusion and resources to go further

Although many things have been discussed in this article, it is possible to go further in setting up your file .htaccess.

I want to remind you to make your changes with extreme attention. Errors or inconsistencies may occur depending on the host of your website.

Periodically keep a backup of the original .htaccess file to perform a restore in case of problems (I will warn you!).

Well, it was a sacred item, is not it? Thank you for having read it in full 🙂

If you had used some more code for your sites, share the pieces of code via comment😉

Leave a Comment

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