Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

How to Use htaccess File to Secure, Optimize, and Control Redirects in WordPress

August 21, 2019

11 Min Read
wordpress htaccess
Reading Time: 11 minutes

The .htaccess is an important WordPress core file that is often used to add, modify and override server-level configurations, security and performance parameters.

In many cases, you can resolve many server-level operational issues and challenges by simply updating/changing rules in the WordPress htaccess file. However, many website owners are not aware of the full potential of .htaccess for WordPress and thus miss out on optimizing their server (and website) to the fullest.

To help all such WordPressers, I will highlight several interesting things you could accomplish by using the .htaccess file in WordPress.

What is a .htaccess File?

A .htaccess file is the control room for your website that contains essential rules that govern all communication with your WordPress web hosting server. In particular, you can use the .htaccess file in WordPress for tasks such as controlling access to website pages, improve security and performance. It can be placed in any folder of your website to change the behavior of that folder.


A single misplaced dot (.) can potentially bring down your website. Thus before making any changes to the .htaccess file, back up the file first to an offsite location. If anything goes wrong, or you need help, contact your web hosting provider.

The Default WordPress htaccess File

.htaccess file comes with every WordPress installation and is generally located in the root directory. Given the importance of htaccess, it is generally hidden (it doesn’t have any file extension) and does not appear in the file and folder listings, mainly because the file manager hides it for security reasons.

In rare cases, it is possible that there is no .htaccess file in the root folder. If this is the case with you, you can create .htaccess file in WordPress using Notepad (or any text editor of your choice) and save it with the name “.htaccess”. Set the Save as type to All files and upload it to the root directory of your WordPress installation.

Save as .htaccess

IMPORTANT: Make sure that the file name is NOT “htaccess” – its htaccess with a period (.) at the start.

Here is how the default WordPress htaccess file looks like:

# 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
# END WordPress

Default WordPress .htaccess file

Another way of creating the .htaccess file for WordPress is to visit WordPress Dashboard -> Settings -> Permalinks and click ‘Save Changes’.

This will generate the default .htaccess file for WordPress inside the root directory.

The WordPress default .htaccess file only handles permalinks of your website. However, this can be changed and additional rules can be added to control how Apache web server handles operations related requests.

How to Edit .htaccess File in WordPress?

To edit .htaccess file in WordPress, go to your root directory. This can be done by using the file manager provided by your WordPress hosting provider or via an FTP client like FileZilla.

Log into your web hosting account, navigate to ‘public_html’ folder and look for the .htaccess file in WordPress installation.

Right-click and click on ‘View/Edit’ option to open it in your preferred text editor.

Make the required changes and save it.

Another way of editing the WordPress .htaccess file is to make a copy of the local system. Once you are done, replace the live version using FTP or file manager.

WordPress htaccess Redirects

As discussed above, the .htaccess file in WordPress can be used to control website redirects. Here are a few frequently used rules that help you set up and control redirections on your WordPress websites.

301 (Permanent) Redirect

A 301 Redirect tells search engines that a URL has been permanently moved to another location. This is not limited to URLs only and you can redirect a folder, page or even a complete website. Below snippet will redirect the oldpage.html to newpage.html:

Redirect 301 /oldpage.html

302 (Temporary) Redirect

Unlike 301, the 302 Redirect tells search engines that this redirection is temporary. This is a great way of slowing down (or even preventing) SERP shuffles. Add the following line to .htaccess file:

Redirect 302 /oldpage.html

Force URL to www

The below-mentioned .htaccess rule in WordPress will force all the visitors on to use

RewriteEngine on
RewriteCond %{HTTP_HOST} ^ [NC]
RewriteRule ^(.*)$$1 [L,R=301,NC]

Force URL to non-www

The below-mentioned WordPress .htaccess rule will force all visitors on to use

RewriteEngine on
RewriteCond %{HTTP_HOST} ^ [NC]
RewriteRule ^(.*)$$1 [L,R=301]

Force HTTPs

The below-mentioned rule in the WordPress .htaccess file will force all your visitors to use HTTPS instead of HTTP for all URLs.

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

Read more: Learn how to add an SSL certificate to a WordPress website.

Force HTTP

The below-mentioned rule in the htaccess file for WordPress will force your visitors to use HTTP instead of HTTPS for all URLs.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} ^https$
RewriteRule .* http://%{HTTP_HOST}%{REQUEST_URI}</IfModule>

Redirect Domain To Sub-Directory

The below-mentioned rule will redirect the domain’s root URL to WordPress htaccess subdirectory of your choice.

RewriteCond %{HTTP_HOST} ^$
RewriteCond %{REQUEST_URI} !^/sub-directory-name/
RewriteRule (.*) /subdir/$1

Redirect a URL

If you have two domains serving the same website, the below-mentioned .htaccess rule will redirect one domain to the other.

Redirect 301 /

WordPress htaccess Security Tips

The WordPress htaccess file can also be used to secure directories and files on the server. Here are a few very important rules that users can deploy to secure WordPress websites.

Protect .htaccess

The .htaccess file can potentially control the entire website. Given this, It is paramount that .htaccess should be protected from unauthorized users. By using the below-mentioned snippet, you can restrict access for all unauthorized users.

Just copy and paste the snippet into the .htaccess file.

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

Restrict Access to WordPress Admin Panel

Imagine the (horrible) scenario where someone gains access to your WordPress admin panel? Such an attack can wreak your website.

To prevent this, you should restrict access to the WordPress admin panel to a specific IP(s) only.

For this, create another .htaccess file, and paste the below snippet in it. Next, upload it to “” folder.

# Limit logins and admin by IP
order deny,allow
deny from all
allow from xx.xx.xx.xx

Now if anyone who is not on the approved IP list, he will not be able to login to your site. Instead, the following error would be displayed:

Internal Server Error

Note: Don’t forget to replace “xx.xx.xx.xx” with your allowed IP address.

You can easily get your IP by visiting “What is my ip”. If you’ve got more than one moderator, you can also add multiple IP’s by using the following variation:

allow from

Secure Important Files

You could use .htaccess in WordPress to protect important files such as error logs, wp-config.php, and php.ini. For this, use the following snippet:

<FilesMatch "^.*(error_log|wp-config\.php|php.ini|\.[hH][tT][aApP].*)$">
Order deny,allow
Deny from all

Protect wp-config.php

In WordPress, wp-config.php is the file where the hosting, database and other important credentials are saved. It goes without saying that this file should be protected from all unauthorized access.

For this, simply copy and paste the following lines in the WordPress htaccess file.

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

Protect /wp-content/

wp-content is the folder that contains all the important files of your themes, plugins, media and cached files. That’s why this directory is the main target for hackers and spammers. To protect this folder from unauthorized access, create a separate .htaccess file in the wp-content folder. Next, copy and paste the below-mentioned snippet in the file:

Order deny,allow
Deny from all
<Files ~ ".(xml|css|jpe?g|png|gif|js)$">
Allow from all

With the above rule, users would only be able to upload files with the allowed extensions (XML, CSS, JPG, JPEG, PNG, GIF, and Javascript). All other file types will be denied.

Protect Include-Only files

Some areas of the WordPress installation should never be accessible by the average users. It is always a good practice to block all access to these files. You can set up the access restrictions by adding the snippet to the .htaccess file.

<IfModule mod_rewrite.c>
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]

Disable PHP Execution

Restricting the execution of PHP code for all or selected directories of the WordPress website is an important WordPress website security practice. Create an htaccess file inside a folder where you don’t want to run PHP scripts, and add the below snippet in it.

<Files *.php>
deny from all

Certain WordPress folders such as /wp-includes/ and /wp-content/uploads/ are writable by default. This type of permission allows users to upload media or different file types. It is always recommended to disable PHP execution on these directories.

File Access Restriction

Restricting access to wp-admin is an important requirement, particularly when several team members are involved in website management and updates.

In practical terms, this means that the users cannot access sensitive files such as plugins, themes, and assets folder.

.htaccess is a great way of protecting direct access to edit PHP files of plugins and themes. Making it harder for hackers to add malicious code. For this, just add the following lines to the file:

RewriteCond %{REQUEST_URI} !^/wp-content/plugins/file/to/exclude\.php
RewriteCond %{REQUEST_URI} !^/wp-content/plugins/directory/to/exclude/
RewriteRule wp-content/plugins/(.*\.php)$ - [R=404,L]
RewriteCond %{REQUEST_URI} !^/wp-content/themes/file/to/exclude\.php
RewriteCond %{REQUEST_URI} !^/wp-content/themes/directory/to/exclude/
RewriteRule wp-content/themes/(.*\.php)$ - [R=404,L]

Script Injection Protection

Script Injection is a notorious technique in which the attacker “injects” a malicious piece of code in the website code to extract data or to take over the website. Adding the following snippet in the WordPress .htaccess file can protect your site from such attacks.

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]
RewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR]
RewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2})
RewriteRule ^(.*)$ index.php [F,L]

Block IP Address

If someone is abusing your website, continuously spamming or launching hacking attempts, their IP is visible in the WordPress admin panel. To block the IP, simply use the .htaccess file to control access to your website. Simply copy & paste the below-mentioned snippet into the WordPress htaccess file and this particular problem will go away. Remember to replace the sample IP with that of the spammer’s.

<Limit GET POST>
order allow,deny
deny from 123.456.78.9
allow from all

Once the snippet is in place, the spammer would see the following error message on your site:

Forbidden Error

Deny Access To Certain Files

Sometimes, you want to restrict access to certain files. Use the below-mentioned .htaccess rule to block access to individual files.

<files your-file-name.txt>
order allow,deny
deny from all

Disable Directory Browsing

Unauthorized access to website files and folders is a major security risk that can potentially bring down the entire site.

By adding the below-mentioned snippet to your WordPress .htaccess file, access to website directories can be controlled/disabled for all users.

# disable directory browsing
Options All -Indexes

WordPress htaccess Rules for Performance

The WordPress htaccess file can also be used to enhance your website performance. Just copy & paste the below-mentioned codes in .htaccess file for each of the options.

Why Speed is Crucial for SEO & UX?

These expert tips will show you how to improve the speed of your WordPress Websites.

Thank You

Your Ebook is on its Way to Your Inbox.

Enable Browser Cache

The browser cache is temporary storage on your system for the files downloaded by your web browser to render websites properly. These files may include HTML, CSS, JavaScript, as well as images and other multimedia content.

In the WordPress .htaccess file, you can set rules for how long certain files should be cached. The following expiry limits are set based on popular usage. To enable browser caching, add the following snippet into the htaccess file for WordPress.

<IfModule mod_expires.c>
        ExpiresActive on
        ExpiresDefault                                    "access plus 1 month"

    # CSS
        ExpiresByType text/css                            "access plus 1 year"

    # Data interchange
        ExpiresByType application/json                    "access plus 0 seconds"
        ExpiresByType application/xml                     "access plus 0 seconds"
        ExpiresByType text/xml                            "access plus 0 seconds"

    # Favicon (cannot be renamed!)
        ExpiresByType image/x-icon                        "access plus 1 week"

    # HTML components (HTCs)
        ExpiresByType text/x-component                    "access plus 1 month"

    # HTML
        ExpiresByType text/html                           "access plus 0 seconds"

    # JavaScript
        ExpiresByType application/javascript              "access plus 1 year"

    # Manifest files
        ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds"
        ExpiresByType text/cache-manifest                 "access plus 0 seconds"

    # Media
        ExpiresByType audio/ogg                           "access plus 1 month"
        ExpiresByType image/gif                           "access plus 1 month"
        ExpiresByType image/jpeg                          "access plus 1 month"
        ExpiresByType image/png                           "access plus 1 month"
        ExpiresByType video/mp4                           "access plus 1 month"
        ExpiresByType video/ogg                           "access plus 1 month"
        ExpiresByType video/webm                          "access plus 1 month"

    # Web feeds
        ExpiresByType application/atom+xml                "access plus 1 hour"
        ExpiresByType application/rss+xml                 "access plus 1 hour"

    # Web fonts
        ExpiresByType application/font-woff2              "access plus 1 month"
        ExpiresByType application/font-woff               "access plus 1 month"
        ExpiresByType application/       "access plus 1 month"
        ExpiresByType application/x-font-ttf              "access plus 1 month"
        ExpiresByType font/opentype                       "access plus 1 month"
        ExpiresByType image/svg+xml                       "access plus 1 month"


Read more: Learn how to Leverage Browser Caching in WordPress to Optimize Page Load Time

Enable Gzip Compression

Gzip is an extremely powerful compression algorithm that locates similar strings within a text file and replaces them temporarily to reduce the overall file size. As a result, Gzip is often used as an important website page load speed optimization tool.

Gzip compression is often used on the server level and many hosting providers like Cloudways enable it by default. However, if for any reason htaccess not working, try adding the below-mentioned snippet to the WordPress .htaccess file or contact your web hosting provider.

<IfModule mod_deflate.c>

  # Compress HTML, CSS, JavaScript, Text, XML and fonts
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml

  # 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


Control/Restrict Image Hotlinking

Image hotlinking can significantly affect the bandwidth usage numbers of your server because every time an external resource requests for an image, your server bandwidth is utilized for delivering the image.

To reduce bandwidth consumption because of image hotlinking, you can add the following code snippet to .htaccess file:

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

htaccess for WordPress Multisite (WPMU)

The default .htaccess file for WordPress Multisite is slightly different from the standard WordPress .htaccess file.

Default htaccess for WPMU Subfolders

If your WordPress Multisite network is subfolders-based, the default .htaccess file should look something like:

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]

Default htaccess for WPMU SubDomains

If your WordPress Multisite network is SubDomain based, the default .htaccess file should look something like:

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]

# add a trailing slash to /wp-admin
RewriteRule ^wp-admin$ wp-admin/ [R=301,L]

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule . index.php [L]

Final Thoughts!

When it comes to server configuration, WordPress .htaccess file is one of the most important files on your server. It is often used for configuring your web server and securing various areas of your website. If you think I have overlooked an important .htaccess use case, do leave a comment below and I will update this list.

Q. What is .htaccess file in WordPress?

.htaccess file in WordPress is a server configuration file which can be used for different kind of redirections, security, and performance.

Q. How can I edit the WordPress htaccess file?

The WordPress .htaccess file can be edited via your web hosting file manager or using any text editor. Use an FTP client like FileZilla, and access the root directory. Open the .htaccess file inside any text editor to modify.

Q. Does WordPress create an htaccess file?

Yes, by default WordPress has the .htaccess file. If it’s not in the root directory, go to the WordPress dashboard -> Settings -> Permalinks click on ‘Save Changes’ button to create a new .htaccess file.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Start Growing with Cloudways Today!

We never compromise on performance, security, and support.

Mustaasam Saleem

Mustaasam is the WordPress Community Manager at Cloudways - A Managed WordPress Hosting Platform, where he actively works and loves sharing his knowledge with the WordPress Community. When he is not working, you can find him playing squash with his friends, or defending in Football, and listening to music. You can email him at

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

BFCM 2019