The .htaccess file may seem complicated at first but we’re here to help you simplify its functions. You may be looking to improve domain security, increase organic search visibility or customize specific directories. The good news is the .htaccess file can help with all of these and using our actionable tips below you may go from beginner to experienced expert in no time.
Why is there an .htaccess file?
.htaccess file is a directory-level configuration file supported by several web servers like Apache, used for configuration of site-access and help you customize website features such as logins, password protection, folder directories, linking structure, page redirects, image linking and more.
How to Begin Editing Your .htaccess File?
In order to edit your .htaccess file you will have to download it using a transfer protocol (FTP) client. We recommend using the free FTP client FileZilla as it is lightweight and has all the necessary features. In addition to downloading your .htaccess file, FileZilla allows you to upload new versions and view other folder and files within your domain. With the file at your fingertips the next step is having a text editor such as Microsoft WordPad. This will allow you to alter the code as needed. We strongly recommend saving an unedited version prior making changes which allow you to restore things back to their default if needed. Here are tested and actionable tips to help your website using your .htaccess file:
1 – Page Redirects
Page redirects refer to having a website visitor automatically go from one document to another within your domain. This is very useful for when you have updated pages to publish a new area such as “/cars/” to “/vehicles/”. Your customers may be visiting old or broken pages on “/cars/” which no longer exist and need to be redirected to your current listings at “/vehicles/”. You may use the following code to successfully implement these redirects:
Redirect /cars/ https://www.yourdomain.com/vehicles/
With the above code implemented in your .htaccess file every time a visitor requests a “/cars/” page they will be redirected to your current listings at “/vehicles/”. This saves your visitors and search engines time browsing your website for current listings and may help increase organic search visibility.
2 – Protect Admin Login by IP Address
You may be surprised to find out that the default login page for every WordPress website is https://www.yourdomain.com/wp-admin/. This allows those who are looking to breach your website to easily attempt to login. However, by adding an internet protocol (IP) address exclusion only users from a specific area will be able to view your login page. Here is the code you should add 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 IP address
allow from 12.345.67.890
# whitelist User2 IP address
allow from 09.87.65.432
</LIMIT>
In the above code make sure to update the “allow from 12.345.67.890” with your own IP address. If you have multiple users accessing this page or are accessing it yourself from multiple locations then be sure to update the second user as well “allow from 09.87.65.432”. You can find your own IP address by searching Google “what is my ip address?”.
3 – Disable Directory Traversal
Disabling directory browsing adds another layer of security to your WordPress website. It will help prevent others from viewing your directory, archive or image files in a list which may be used to find a weak spot on your domain security. While obscuring directory listings may not be the end all to avoiding security breaches, it definitely helps deters those who may want to breach your website by making it more difficult. You may implement the following code on your .htaccess file to prevent directories from being viewed:
Options -Indexes
IndexIgnore *.zip *jpg *.gif
It is recommended by most WordPress security experts to add these lines of code to your .htaccess file. Implementing this solution will make you a more difficult target to breach, hopefully deterring any attacker and increasing their chances to move on to an easier domain.
4 – Create Custom Error Pages
We have all had the experience of landing on a page only to find that it does not load properly. These are known as error codes and include the following:
400: Bad Request
401: Authorization Required
403: Forbidden
404: File Not Found
500: Internal Server Error
This may cause a visitor to leave your website and search engines to lower your organic search visibility. You can, however, retain visitor engagement and organic visibility by having helpful error pages. This page would include useful links around your domain such as high level navigation, top articles, commonly purchased items and more. In this example we will use the most common error codes 404: File Not Found and 500: Internal Server Error. You should begin by creating unique landing pages that include site navigation, etc, located at www.yourdomain.com/filenotfound.html and www.yourdomain.com/internalservererror.html respectively. With these pages created you may add the following code to your .htaccess file to bring visitors there when they have encountered an error:
ErrorDocument 404 /filenotfound.html
ErrorDocument 500 /internalservererror.html
You may use the ErrorDocument <number> /landing-page.html code formatting to ensure you cover all bases including 400, 401, 403 and other errors. It will simply look like the examples above with different numbers and landing pages.
5 – Ban An Abuser IP Address
This would be the equivalent of ejecting a bad customer from your store. They may be running a script to slow down your website, sending an abnormal amount of requests or harassing others on the forums or blog comments. Regardless, it is time for them to leave and no longer enter your store. This is done quite easily using the following line of code:
order allow,deny
deny from 12.345.67.89
deny from 71.181.64.80
allow from all
This code will block incoming traffic from the internet protocol (IP) addresses 12.345.67.89 and 71.181.64.80 respectively. They will be shown a 403: Forbidden error page which you may customize using the code found in our Custom Error Pages section. In addition, it will still allow all other users to navigate the website as normal with the “allow from all” line of code found at the bottom.
6 – Disable Image Hotlinking
Image hotlinking refers to other websites directly linking to your images, videos and other non-html assets. This may cause your website to load slower than normal and overuse your hosting bandwidth. Google announced on July 9th, 2018 that their organic search ranking factors included how fast your website loads for all devices. In addition, your page speed has a major impact on visitor engagement and conversion. To ensure other websites are not hotlinking to your images add the following code to your .htaccess file:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?google.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]
It is important to replace //(www\.)?yourdomain.com [NC] with your actual domain address. In addition, the above code still allows Google.com to hotlink to your images to ensure organic search visibility.
If hotlinking is detected you may also use a custom image such as a brand logo to be displayed on their website. Use the following code to have your brand logo appear rather than the hotlinked image:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)yourdomain.com/.*$ [NC]
RewriteRule \.(gif|jpg)$ http://www.yourdomain.com/company-logo.png [R,L]
7 – Increase PHP File Upload Size
As the website administrator you may receive an error when uploading a large file. This includes messages on WordPress such as “warning post content-length of bytes exceeds the limit” or “exceeds the maximum upload size for this site”. This likely stems from your hosting server configuration and can be updated with the following code 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
In addition to allowing larger files, the code increases allotted execution time ensuring your upload does not timeout in WordPress.
8 – Protect WordPress Configuration File
Your wp-config.php file is vital to your website’s security and functionality. It has your database connection information such as DB_NAME, DB_USER, DB_PASSWORD and more as well as configuration for more advanced WordPress options. This makes securing your wp-config.php file very important and as such we recommend adding the following code:
<files wp-config.php>
order allow,deny
deny from all
</files>
The above code specifically denies any access to your wp-config.php file.
9 – Protect .htaccess From Unauthorized Access
There is clearly many ways to manipulate a website using an .htaccess file. As such we want to make sure the file itself is protected. The following code will prevent outside users trying to access the file:
<files ~ "^.*\.([Hh][Tt][Aa])">
order allow,deny
deny from all
satisfy all
</files>
This code denies access to all files beginning with Hh Tt Aa including your .htaccess file
10 – Disable XML-RPC Access
XML-RPC files are installed by default on every WordPress website. These files allow your website to utilize third-party apps or plugins such as Google Analytics for WordPress. Third-party apps are a common method for hackers to use when infiltrating a website. You may remove this function from your WordPress website with the following code implemented onto your .htaccess file:
<Files xmlrpc.php>
order deny,allow
deny from all
</Files>
It depends on configuration but your WordPress theme may be considered a third-party app or plugin. As such we recommend confirming with your developer, theme vendor and saving a backup .htaccess file to restore as needed.
11 – Redirect Visitors to Maintenance Page
Your domain may be in startup mode or you are temporarily rebuilding your website. This leaves your domain and incoming traffic in an awkward phase. Instead of having consumers and search engines arriving to a dead page, you may temporarily redirect them to a maintenance page displaying your launch date and other useful links. This also prevents search engines from indexing your broken or maintenance pages. Here is the recommended code:
RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.html$
RewriteCond %{REMOTE_ADDR} !^123\.123\.123\.123
RewriteRule $ /maintenance.html [R=302,L]
You will have to make three updates to the code above. On the second and fourth lines the maintenance live page is being pulled in. The default code above will send users to www.yourdomain.com/maintenance.html; however if your maintenance or splash page lives elsewhere you must change the destination. An example would be having a live page at /splash/ and updating the code from:
OLD: RewriteCond %{REQUEST_URI} !/maintenance.html$
NEW: RewriteCond %{REQUEST_URI} !/splash/$
The second update would be implementing your IP address on the third line. This will ensure you have access to your own website while the maintenance page is displayed to all other incoming traffic.
12 – Block Scans of Blog Author Name
It is common for domains to have multiple authors contributing to the site. This allows for team collaboration as you can see which admin edited which page and which author contributed to which blog post. On the other hand, it allows a hacker to identify several usernames and then begin attempting to discover the password for each. These user scans may be prevented by implementing the following lines of code:
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} (author=\d+) [NC]
RewriteRule .* - [F]
We still recommend using multiple authors and users as needed for your website. The above code is simply there to prevent hackers from scanning usernames. This adds another security measure and makes it less likely for your website to be breached.
13 – Correct URL Typo Automatically
Consumers are navigating the internet at incredibly quick speeds. Unfortunately, that means there is a typo created here and there. When a consumer shares or visits an incorrect page URL they are typically navigated to a 404 error page not found. You can keep consumers on track while navigating your website using the following code:
<ifmodule mod_speling.c>
CheckSpelling On
</ifmodule>
The above code works extremely well when a consumer types in www.yourdomain.com/carf/ instead of www.yourdomain.com/cars/. Instead of having to navigate through a broken page they will simply be redirected to the page displaying cars. The above code does not work in situations where the misspelling is far off such as /cfarsdr/ to /cars/.
14 – Secure WordPress Plugin Files
WordPress is one of the most popular content management systems due to their integration with third-party plugins. While these third-party plugins enable you to completely customize your website, they do leave you vulnerable to security breaches. While not common, a few WordPress plugins allow access to unauthorized users posing a major security threat. The following code will prevent others from having access to plugin files:
<files ~ ".(js|css)$"="&”.(js|css)$&">
order allow,deny
allow from all
</files>
We strongly encourage you to keep your plugin up to date and report any potential security issue to the developer.
15 – Add a Slash to the End of URL
Search engines give priority to websites with a clean and consistent URL structure. Websites may run into duplicate content issues if there are multiple versions of a single page such as yourdomain.com/ and yourdomain.com. In order to standardize all your trailing slashes we recommend adding the following code:
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !#
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://domain.com/$1/ [L,R=301]
This will force all pages to end with a trailing slash and have a clean structure across your domain. If a visitor types in yourdomain.com it will permanently redirect to yourdomain.com/.
16 – Prevent Spammers from Posting on Your Blog
In the fifth trick we covered banning specific IP addresses to prevent known abusers from accessing your website. If you are not able to identify a spammers IP address here is an additional trick to prevent them from accessing your website:
RewriteEngine On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} .wp-comments-post.php*
RewriteCond %{HTTP_REFERER} !.*yourblog.com.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]
The above code targets bots that are designed to only leave irrelevant comments on blogs. When a comment bot visits a page it only requests the comment dialogue box. The bot only requests this element as it does not want to load the rest of the page. The code above denies users seeking a single request from a page. The final line of code refers to where bots should be redirected.
17 – Customize Permalinks for Friendly URLs
Google and other search engines recommend having clean and consistent page URLs for high organic search visibility. You may edit your .htaccess file to alter your link structure and have pages include relevant keywords rather than characters such as “&” and “%”. In addition, using your .htaccess file will circumnavigate the default settings created by WordPress. Here is the code for customizing permalinks:
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
An example page may be updated from “www.yourdomain.com/cars%/re%/” to www.yourdomain.com/cars/red/. The second page is more likely to rank higher in organic search for terms such as “red cars”. We strongly recommend you have your current pages mapped out prior to publishing.
18 – Disable PHP Execution in Media Directories
In general, hackers attempting to compromise your website will try to do so by installing a php based backdoor file somewhere deep in your directory structure. This makes it difficult to spot and remove. You may prevent the hacker’s backdoor execution by implementing the following code in .htaccess file placed in those directories that should not have php file in them like the media directory /wp-content/uploads/
<files *.php>
deny from all
</files>
The code above prevents all unauthorized files from running PHP scripts thus ensuring safety of your domain.
19 – Enable Browser Caching
Consumers expect their information to load immediately. Browser caching will increase page speed as common images such as a company logo are stored on your consumer’s local drive. This allows the consumer to navigate from page to page without having to redownload commonly used assets. You can implement user side caching using the following code:
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"
The expiration dates in the code above refer to how long a consumer will store certain files on their local drive. It is recommended to store an image file for one year and most other web elements for a month. You should also note that a consumer may delete their temporary files by clearing the cache on their web browser.
20 – Enable HTTP Compression
We have mentioned that consumers expect their information immediately. Google has even made load times part of their organic search algorithm as announced here. Thankfully you may use this trick to compress files into smaller sizes and ultimately make your pages load quicker. Here is the code to be implemented:
<ifmodule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml application/xml application/xhtml+xml text/javascript text/css application/x-javascript application/javascript
</ifmodule>
The above example is specific to GZIP compression and requires mod_deflate Apache module enabled for your website.
21 – WWW Redirect
Without www redirect search engines may crawl duplicate versions of a single page, causing them to interfere and compete in the organic search listings. An example would be having both www.yourdomain.com and yourdomain.com accessible as two valid URL. You may redirect all non-www versions of your website to the www version by adding the following code:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
In the above example you will need to replace example.com on the third line with your specific domain name.
22 – Force HTTPS SSL Redirect
HTTPS SSL refers to a secure socket layer which increases your website’s security. This protects your consumers’ data as well as helps avoid man in the middle attack on your website. Google even gives organic search priority to websites that are secure. Here is the code to force your HTTPS SSL version to be shown:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]
This also prevents duplicate content being live on both www.yourdomain.com/cars and https://www.yourdomain.com/cars. As such search engines are more likely to properly crawl and index your website.
23 – Prevent Code Injections
Code injections are attacks on your domain which have a wide variety of purposes. The script may be used to discover login information, breach your database, display pop-up messages to incoming traffic and more. They specifically target elements within your HTML, CSS, Javascript or SQL database. The following htaccess rewrite rules prevents unauthorized code injection from running on your website:
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]
In this trick you do not need to edit any of the above code to fit your website. You can simply copy and paste this into your .htaccess file to prevent code injections.
24 – Reduce Server Load using FeedBurner for RSS
Your RSS feed is a great way to stay connected with consumers. They are able to engage with your content using their preferred method. However, default RSS feeds typically cause a lag between a consumer’s request and the server’s response time. This ultimately slows down your server. You may use another service such as Google Feed Burner with the following code:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} !^.*(FeedBurner|FeedValidator) [NC]
RewriteRule ^feed/?.*$ http://www.example.com/feed [L,NC,R=301]
</IfModule>
In the above code it is important to update the fourth line with your domain and RSS Feed URL.
25 – Block Brute Force Attacks
With WordPress being such a common content management system (CMS) or website platform, it has naturally become a target for hackers to crack. The most common effort is running a script which attempts logins over and over. This causes your server to overload and the hacker may find out your password. You may add the following lines of code to prevent these brute force attacks:
RewriteEngine on
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{HTTP_REFERER} !^http://(.*)?example\.com [NC]
RewriteCond %{REQUEST_URI} ^(.*)?wp-login\.php(.*)$ [OR]
RewriteCond %{REQUEST_URI} ^(.*)?wp-admin$
RewriteRule ^(.*)$ - [F]
In the above example you will need to update the third line from example\.com to your domain (without www). In the above scenario a hacker is attempting logins without ever visiting your website. This script prevents anyone from direct access and requires that the user submitted the login form on your website.
If you would prefer only known IP addresses to be able to attempt to login you may add the following code:
RewriteEngine on
RewriteCond %{REQUEST_URI} ^(.*)?wp-login\.php(.*)$ [OR]
RewriteCond %{REQUEST_URI} ^(.*)?wp-admin$
RewriteCond %{REMOTE_ADDR} !^123\.123\.123\.123$
RewriteRule ^(.*)$ - [R=403,L]
You must update line four with your actual IP address. You may find your IP address by searching on Google “What is my IP address?”. In addition, you may add multiple IP addresses simply by adding another line below.
26 – Prevent Unauthorized wp-admin and wp-login.php Attempts
You may add another layer of security by preventing unauthorized access to admin login. If you are not an authorized user you will be given an error page such as 401 Unauthorized or 403 Forbidden. You will need access to your hosting files and add the following code to your .htaccess file under wp-admin directory:
ErrorDocument 401 "Unauthorized"
ErrorDocument 403 "Forbidden"
# Allow admin-ajax.php access
<files admin-ajax.php>
Order allow,deny
Allow from all
Satisfy any
</files>
In addition, you will need to add the following code to your .htaccess file under the public_html directory:
ErrorDocument 401 "Unauthorized"
ErrorDocument 403 "Forbidden"
<filesmatch "wp-login.php">
AuthType Basic
AuthName "WordPress Admin"
AuthUserFile "/home/USERNAME/.htpasswds/public_html/wp-admin/passwd"
require valid-user
</filesmatch>
The above code this adds another layer of security to prevent hackers from breaching your website.
27 – Set the Time Zone according to your location
If you host your website on a server located at a different time zone than your primary business location, you can set the time zone in .htaccess to reflect your local time zone as follow:
php_value date.timezone America/New_York
The above line in will set the time zone to New York. A full list of all supported php timezones can be found at the following website: http://php.net/manual/en/timezones.php
Conclusion
With all of the above information clearly the .htaccess file has quite a bit of functionality to customize your WordPress website. If you are having difficult implementing a more custom solution just leave us a note and we would be happy to assist!
Do you have a htaccess tips you like to share with other people to improve their WordPress website? Feel free to let us know below!
Get started with Premium WordPress hosting for your Business today
We are using feedburner but dont have any code in htaccess file for this. Is it a must?
What about multilangual sites? .com/feed and .com/en/feed
RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} !^.*(FeedBurner|FeedValidator) [NC]
RewriteRule ^feed/?.*$ http://www.example.com/feed [L,NC,R=301]
thanks
Thanks for this Very Useful head-Up on WordPress .Htaccess Tricks, well…, much more than a Tricks.
Glad to still find Olda Skool fella ( no plug-bug do-it-All )
@lorenzocoffee Cheers to that & big boo to the plugin loo 🙂