A Complete Comprehensive Guide for Editing .htaccess for WordPress to achieve best Security and SEO.
WordPress is the the most widely used Content Management System (CMS) in the world. A huge number of website build on WordPress platform. It’s the only platform On which Technical and Nontechnical both can build, verity of websites like eCommerce, Blogging, Portfolio etc, Naturally due to its popularity, is an incredibly attractive target for hackers. Most of the WordPress users don’t have any technical knowledge. That’s the reason why hackers easily hack their websites.
Today, I’ll explain a bit about securing WordPress website and some tips for SEO purpose using .htaccess file. This file is not used only for the security purpose, there are many other concepts which can be applied. You will learn about those too. When i was a newbies in development, I called it The Magic File
I am writing this post for both technical and nontechnical user, i had described some point in depth, so technical users might be know some of points. Let’s Start
What is .htaccess File and How you can Edit it?
An .htaccess file is an optional configuration or setting file for the Apache web server to interpret, for each directory. You can store various server settings in this file. By default the .htaccess file is present in the base WordPress installation root directory.
.htacess is a configuration file that allows you to override your server’s global settings for the directory that it’s in,
by limiting file access.
First of all show hidden files in cpanel, go to
Settings -> Check “Show Hidden Files” – > Save
TIP: Before you start with the tutorial, make sure to backup the current .htaccess file. This is to roll back to the last known working .htaccess file, if a certain code snippet breaks your site. Let’s begin. I personally request you update every block very carefully, a wrong entry can stop working of your website.
When you edit .htaccess file, this code generated by WordPress and you’ll find it in almost every .htaccess file:
1 2 3 4 5 6 7 8 9 10 |
# 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 |
Let’s start editing with the magic .htaccess file, here is a quick glance of what we will discuss in this tutorial.
- Protect .htaccess Itself
- Disable Hotlinking with .htaccess
- Protect wp-config.php file with .htaccess:
- Prevent Directory Browsing Listing
- Restrict Access to Admin Area / Restrict Access to WP Admin directory by using IP Address
- Stop Spammers using .htaccess
- Disable PHP Execution for Some WordPress Directories
- Setting up 301 Redirects Through .htaccess File
- Increase File Upload Size in WordPress using .htaccess
- Block Bad Bots or Restrict Suspicious IP Addresses using .htaccess
- Protecting /wp-contents/
- Disable Access to XML-RPC File Using .htaccess
- Protect wp-include files
- Protect Your Website Against Script Injections
- Enable Leverage Browser Caching, to make your website faster
1. Protect .htaccess Itself:
.htaccess has the control to manage and access your whole website. It is important to first protect this file from unauthorized users. By using the snippet below, you can restrict access to unauthorized users.
Just copy and paste the snippet below into your .htaccess file.
1 2 3 4 5 |
<files ~ "^.*\.([Hh][Tt][Aa])"> order allow,deny deny from all satisfy all </files> |
2. Disable Hotlinking with .htaccess:
You may encounter a situation that your other blogger or other website use your images, and displays these images using your absolute original URL. Means this resources will called from server. When visitors load these images on his site, the usage of bandwidth is from your website. This is called as Hotlinking.
To prevent your bandwidth from being stolen by other webmasters, you should enable hotlink protection using .htaccess. To do this, you can add the following content in the .htaccess file.
1 2 3 4 5 6 7 |
RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?YourDomain.com [NC] RewriteRule \.(jpg|jpeg|png|gif)$ – [NC,F,L] |
Don’t forgot to replace YourDomain.com keyword with your site name. when people try to access your domain file, there is a 403 forbidden error opening on their view.
3. Protect wp-config.php file with .htaccess:
WordRress wp-config.php file contains all critical information about your database, including username, password, host and database name. This file is very important because this information is used to enable data store and retrieve. Thus, you have to take this file seriously, or your site will be in danger. The following lines tell how to strengthen wp-config.php with .htaccess.
1 2 3 4 5 6 7 |
<Files wp-config.php> order allow,deny deny from all </Files> |
4. Prevent Directory Browsing Listing using .htaccess:
Prevent Directory Browsing Listing is good, your user should not see the directory listing. With this code you’ll prevent any directory browsing listing.
1 2 |
# directory browsing Options All -Indexes |
5. Restrict Access to Admin Area / Restrict Access to WP Admin directory by using IP Address using .htaccess
The admin area is a private and confidential place of any website, which enables full access for you to handle all administrative functions. As everyone know /wp-admin is Admin login URL, Hackers and spams can attacke directly. However, there are also some other user roles available in wordpress like editor, author, subscriber and author having partial access. To prevent this access you can allow wp-admin for specific IP address only.
To do this, you can add the following code to the .htaccess file and change your IP address.
1 2 3 4 5 |
order deny,allow allow from {XXX.XXX.XX.XXX} deny from all |
You can also change default WordPress wp-admin login URL with my another tutorial for WordPress security.
6 Stop Spammers using .htaccess:
Like Hotlinking, spammers are also use up your site’s resources and bandwidth. There are a lots of plugin available in market to stop spamming for comments and registration, a number of ways to identify a potential spammer. One of them is to detect requests with ‘no referrer’ if request source is from nowhere, it might be a spammer trying to access your site. Spammers use bots to post comments on blogs and they come from ‘nowhere’. Add these lines to stop the spammers, Please change yoursite.com to your website name.
1 2 3 4 5 6 |
RewriteEngine On RewriteCond %{REQUEST_METHOD} POST RewriteCond %{REQUEST_URI} .wp-comments-post\.php* RewriteCond %{HTTP_REFERER} !.*yoursite.com.* [OR] RewriteCond %{HTTP_USER_AGENT} ^$ RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L] |
7. Disable PHP Execution for Some WordPress Directories
Sometimes hackers break website security from WordPress core files and directories. WordPress files and are stored in /wp-includes/ or /wp-content/uploads/ folders.
An easier way to improve your WordPress security is by disabling PHP execution for some WordPress directories. For this You need to create a blank .htaccess file on your local computer and then paste the following code inside that directory.
1 2 3 |
<Files *.php> deny from all </Files> |
8. Setting up 301 Redirects Through .htaccess File
301 Redirects method of redirection is used when you have moved any resource or change any URL. 301 redirects is the most SEO friendly way to tell your users or visitor, that a content has been moved to a new location. In this you do not loos your visitor after changing the URL.
all you need to do is paste this code in your .htaccess file.
1 2 |
Redirect 301 /oldurl/ http://www.example.com/newurl Redirect 301 /category/wordpress/ http://www.example.com/category/wordpress/ |
9. Block Bad Bots or Restrict Suspicious IP Addresses using .htaccess
If you seeing unusually high requests to your website from a specific IP address? You can easily block those requests by blocking the IP address in your .htaccess file.
One of the best uses of the .htaccess file is its ability to deny multiple IP addresses from accessing your site. This is useful when blocking known spammers and other origins of suspicious or malicious access. The code is:
1 2 3 4 5 6 |
<Limit GET POST> order allow,deny deny from xxx.xxx.xx.xxx deny from ***.***.**.*** allow from all </Limit> |
10. Increase File Upload Size in WordPress using .htaccess
There are different ways to increase the file upload size limit in WordPress. You can also update default max upload file side from server setting. But if you have shared hosting you can’t set it. this method is very useful for those who have host their website on share hosting.
you can do this by simply adding following code in to .htaccess file:
1 2 3 4 |
php_value upload_max_filesize 128M php_value post_max_size 128M php_value max_execution_time 500 php_value max_input_time 500 |
This code simply tells your web server to use these values to increase file upload size as well as maximum execution time in WordPress.
11. Protecting /wp-contents/
wp-content is the WordPress folder which hold or contains all off your themes, plugins, media and cached files.
That’s why this directory is the main target for hackers and spammers. You can stop it by creating a separate .htaccess file. Copy and paste the snippet below, in that file, and keep that file in wp-content directory.
1 2 3 4 5 |
Order deny,allow Deny from all <Files ~ ".(xml|css|jpe?g|png|gif|js)$"> Allow from all </Files> |
This code snippets allow only media files including XML, CSS, JPG, JPEG, PNG, Gif, and Javascript. All other file types will be denied.
12. Disable Access to XML-RPC File Using .htaccess
In WordPress installation a file called “xmlrpc.php” is also installed. This file is responsible for allowing third-party apps to connect to your WordPress site. If you site is not using any third party apps, then you should disable this feature.
There are multiple ways to do that, one of them is by adding the following code to your .htaccess file:
1 2 3 4 5 |
# Block WordPress xmlrpc.php requests <Files xmlrpc.php> order deny,allow deny from all </Files> |
13. Protect wp-include files:
There are some private areas in WordPress like wp-include, wp-admin, that never should accessed by the user and hackers. You should block this areas for security.
You can blocks those areas by adding the snippet below, into your .htaccess file.
1 2 3 4 5 6 7 8 9 |
<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/ - [F,L] </IfModule> |
14. Protect Your Website Against Script Injections using .htaccess
Like SQL injection, Spammers and hackers can inject some malicious code into your PHP files. The WP Recipes posted a way to prevent script injections on this files. Many hackers try to change your your WordPress GLOBALS and _REQUEST variables in an attempt to inject malicious code.
You can add the following to your .htaccess file to prevent this change from being accepted:
1 2 3 4 5 6 |
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] |
15 Enable Leverage Browser Caching, to make your website faster
This is also known and client-side caching or browser cache. This Technic is used for reduce site loading time. You can learn more about Fix Leverage Browser Caching Warning, to make your website faster in my other post.
Place this code snippets in .htaccess file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Setup browser 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 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 2 days" </IfModule> |
15 . Custom Error Pages
You can also use the .htaccess file to redirect custom error pages for errors such as 403, 404 and 500 etc. You only need to add the following code snippet to your .htaccess file to enable the custom error page:
1 2 3 4 |
# Custom error page for error 403, 404 and 500 ErrorDocument 404 /error.html ErrorDocument 403 / error.html ErrorDocument 500 / error.html |
Wrapping Up
Hope this code spinnerets will help you to secure your WordPress site and helping to improve SEO. Really htaccess is a magic file, what you say…? If you have any more tips and tricks related to .htaccess file please comment below.
[paypal-donation]
Your work is great inspiration for me. I like it! Thanks for sharing, very helpful.
Most welcome and Glad to see you here.