The .htaccess file is a configuration file that allows you to control files and folders in the current directory, and all sub-directories. The filename is a shortened name for hypertext access and is supported by most servers.
For many WordPress users, their first meeting with the .htaccess file is when they customize their website’s permalink settings. To get those pretty permalinks that we all know and love (e.g. https://www.elegantthemes.com/sample-post/ instead of https://www.elegantthemes.com/?p=123), we need to add something like this to the .htaccess file:
01 02 03 04 05 06 07 08 09 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 |
If no .htaccess file exists, you can create one yourself and upload it. All you have to do is create a blank text file, save it as .htaccess and upload it to the root of your WordPress installation. Be sure to include the period at the start of the filename (i.e. save the file as .htaccess and not htaccess).
You also need to ensure your .htaccess file is writeable so that WordPress can add the appropriate permalink code to your .htaccess file. WordPress.org advises file permissions of 644 for the .htaccess file.

The .htaccess file is a hidden file. You therefore need to ensure your FTP client or file manager is configured to display the file in your directory.
The .htaccess file is not only used for permalinks. The file is better known for its ability to strengthen the security of a website. Millions of WordPress users use the .htaccess file to protect their websites from spammers, hackers, and other known threats.
In this article, I would like to share with you several snippets for .htaccess that will make your website secure. I have also included a few additional snippets that I believe you will find useful.
You may have noticed in my permalink example above that the code begins with # BEGIN WordPress and ends with # END WordPress. WordPress can update any code that is placed within those tags. You should therefore add the snippets shown in this article at the top or bottom of your .htaccess file (i.e. before # BEGIN WordPress or after # END WordPress).
Be Careful
The .htaccess file is one of the most temperamental files you will encounter when using WordPress. It only takes one character to be out of place for the code to be incorrect. When that happens, it will usually cause your whole website to go down. It is therefore vital that you copy the code noted in this article correctly to your own .htaccess file.
Even if you are cautious, accidents can happen, and they frequently do.
Do not cut any corners when working with the .htaccess file. Before you begin, make a backup of your current working version of .htaccess. Store it in a safe place on your computer, and if possible, in another location such as a USB flash drive or on cloud storage.
Whenever you update your .htaccess file on your server, refresh your website to see if your website is still live. Do not skip this step as it is vital that you verify your website is still working correctly. If your website returns a blank screen, immediately revert back to your saved copy of .htaccess by uploading it over the version with errors.
If you cannot locate your backup file, either upload a blank .htaccess file or delete the .htaccess file altogether. This will get your website back online; which will obviously be your priority when your website goes offline.
Do not take any chances with .htaccess. Always have a back up. You have been warned 🙂
1. Protect .htaccess
Due to how much control .htaccess has over your whole website, it is important to protect the file from unauthorised users. The following snippet will stop hackers from accessing your .htaccess file. You can, of course, still edit the file yourself via FTP and through your hosting control panel’s file manager.
01 02 03 04 05 | <files ~ "^.*.([Hh][Tt][Aa])" > order allow,deny deny from all satisfy all </files> |
2. Protect WP-Config.php
Another important file is wp-config.php. This configuration file contains the login information for your WordPress database as well as other important maintenance settings. It is therefore advisable to disable access to it.
01 02 03 04 | <files wp-config.php> order allow,deny deny from all </files> |
3. Protect /Wp-Content/
The wp-content directory is one of the most important areas of your WordPress website. It is where vital files are located such as your themes, plugins, uploaded media (images and videos), and cached files.
Due to this, it is one of the main targets of hackers. When a spammer managed to compromise an old website of mine last year, he did it by uploading a mail script to my uploads folder. He then proceeded to send out spam mail using my server; which subsequently placed my server on spam blacklists.
You can tackle threats like this by creating a separate .htaccess file and adding the following code to it:
01 02 03 04 05 | Order deny,allow Deny from all <Files ~ ".(xml|css|jpe?g|png|gif|js)$" > Allow from all </Files> |
You then need to upload this separate .htaccess file to the main wp-content directory i.e. www.yourwebsite.com/wp-content/. Doing this will allow media files to be uploaded including XML, CSS, JPG, JPEG, PNG, Gif, and Javascript. All other file types will be denied.
4. Block Include-Only Files
There are certain files that never have to be accessed by the user. You can block access to these files by adding the following code to your .htaccess file:
01 02 03 04 05 06 07 08 09 10 | # Block the include -only files. <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] </IfModule> |
5. Restrict Access to the Admin Area
Another entry point for hackers is the WordPress admin area. If they gain access to this area, they can do almost anything to your website.
To make this area more secure, create a new .htaccess file and add the code below to it:
01 02 03 04 05 06 | # Limit logins and admin by IP <Limit GET POST PUT> order deny,allow deny from all allow from 12.34.56.78 </Limit> |
Be sure to change 12.34.56.78 to your own IP address (you can find out your IP address at What Is My IP?). Then upload the file to your website’s /wp-admin/ folder i.e. www.yourwebsite.com/wp-admin/.
This will allow you to access your WordPress admin area, but will block everyone else.
Additional IP addresses can be added for other administrators and staff. You can do this by adding additional allow lines or listing their IP addresses in the main allow line and separating them using commas. For example:
01 | allow from 12.34.56.78, 98.76.54.32, 19.82.73.64 |
6. Ban Someone From Your Website
If you know the IP address of a malicious party, you can completely ban them from your website using the snippet below. For example, you could ban someone who always leaves abusive comments or someone who has attempted to access your admin area.
01 02 03 04 05 06 | <Limit GET POST> order allow,deny deny from 123.456.78.9 deny from 987.654.32.1 allow from all </Limit> |
7. Send Visitors to a Maintenance Page
Maintenance plugins such as Ultimate Maintenance Mode and Maintenance are useful for displaying a temporary message to visitors when you are developing a website, or when working in the background to update your website.
Unfortunately, maintenance plugins are of little help if you face the infamous WordPress White Screen of Death. They only function correctly if your website is working correctly.
If you want to prepare for the worst, I recommend creating a basic HTML page named maintenance.html that advises visitors that you are currently experiencing problems with your website, but will be back online soon. When your website does go down because of a hacking attempt or because of the White Screen of Death, simply add the snippet below to your .htaccess file to direct all traffic to your message at maintenance.html.
01 02 03 04 | RewriteEngine on RewriteCond %{REQUEST_URI} !/maintenance.html$ RewriteCond %{REMOTE_ADDR} !^123.123.123.123 RewriteRule $ /maintenance.html [R=302,L] |
You need to configure the above code for your own website. Change the html filename to the name and location of your own maintenance file in the second and fourth row. You also need to add your own IP address to the third row to ensure that you can access your website whilst the maintenance message is being displayed to others. The code uses a 302 redirect ensure that the maintenance page itself is not indexed.
8. Disable Directory Browsing
Allowing unauthorised individuals to look at your files and folders can be a major security risk. To disable browsing of your directories, simply add this small piece of code to your .htaccess file:
01 02 | # disable directory browsing Options All -Indexes |
9. Enable Browser Caching
Browser Caching is something I recently discussed in my article “Optimize Your WordPress Website Using These Simple Tips“. Once enabled, browser caching will allow visitors to save items from your web page so that they do not need to be downloaded again.
It is used for design elements such as CSS stylesheets and media items such as images. It is a practical solution as when someone uploads an image to a website, the image is rarely updated again. Browser caching would therefore allow visitors to load the image saved on their computer rather than your server. This reduces bandwidth and increases page loading times.
To enabling browsing caching, all you need to do is add this code to your .htaccess file:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 | ## 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 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> ## EXPIRES CACHING ## |
10. Redirect a URL
301 redirects allow you to inform search engines that a URL has permanently moved to a new location. They can be used to redirect a page, folder, or even a completely new website.
They are therefore used whenever the URL of a page changes. This can be due to changing a domain, changing the permalink structure of your website, or simply changing the page slug (e.g. changing the page slug of an article from my-news to mygreatnews).
To redirect a location, all you need to do is add a line with Redirect 301, followed by the old location and then the new location. You can see how this works in practice below:
01 02 03 | Redirect 301 /oldpage.html http: //www.yourwebsite.com/newpage.html Redirect 301 /oldfolder/page2.html /folder3/page7.html Redirect 301 / http: //www.mynewwebsite.com/ |
11. Disable Hotlinking
Hotlinking is a practice in which someone shares an image from your website by linking directly to the image URL. It commonly occurs on discussion forums, but many website owners still do it too (which is a mistake as it means images can be removed from your content at any time). Hotlinking can have a negative effect on your website. In addition to slowing your website down, it can also significantly increase your bandwidth costs with your hosting company.
You can prevent hotlinking by only allowing your own website, and any others you own, to execute image files. Add the code below to your .htaccess file to stop others from hotlinking your images. Be sure to replace the URL’s below with your own website addresses.
01 02 03 04 05 | RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^http(s)?: //(www.)?yourwebsite.com [NC] RewriteCond %{HTTP_REFERER} !^http(s)?: //(www.)?yourotherwebsite.com [NC] RewriteRule .(jpg|jpeg|png|gif)$ http: //i.imgur.com/g7ptdBB.png [NC,R,L] |
When someone now views an image of yours at another URL, they will instead be shown the image denoted in the last line of code. This image can be changed to whatever you want.
* Note that disabling hotlinking may cause some RSS readers to have problems displaying your images from your RSS feed.
I hope you have enjoyed this list of tips and tricks for the .htaccess file. As you can see, it is a versatile configuration file that can be used for many things.
If you enjoyed this article, I encourage you to subscribe to the Elegant Themes Blog. Also, please feel free to share your own .htaccess tips and tricks with others in the comment area 🙂
Article thumbnail image by venimo / shutterstock.com
Step by Step Guide to Setup WordPress on Amazon EC2 (AWS) Linux Instance

Amazon Elastic Compute Cloud (Amazon EC2) is a cloud service that provides resizable compute capacity in the cloud. It is designed for developers to scale and monitor their web-application better way.
Amazon EC2 provides some of advanced features like elastic IPs, Load Balancing, various platforms like (linux, windows, etc.), scaling, monitoring etc. It is also easy for developers to manage their web-application in better way.
Hosting WordPress on AWS
is smart choice because as compare to other VPS provider amazon have low pricing, more features and other related amazing services. Also they charge you per hours your instance run.
So, in this tutorial I’ll show you how you can setup LAMP environment on Linux platform and install WordPress blog manually on Amazon EC2 instance.
This step-by-step guide will help you to manage your host completely which is different than cPanel.
1. Create an AWS Account

First of all you need to create your AWS account. You can sign up by following this link. You will have to provide a credit card or international Debit card and a phone number on which you will be called as part of the online registration verification process as par their terms and policy.
Your credit card or debit card will be charge of minor value and it will be refunded once they verify it. Amazon offers a Free Usage Tier on which we will install WordPress, which is great to explore the services and even host real apps without being charged of single penny.
2. Create an Instance
After registration you have many options available and then you probably have this question in your mind that Which type of instance should I choose
?
If you have new blog then you can choose EC2 micro instance
which can handle around 200+ real-time traffic.
It has also attractive price structure but if you are migrating your existing blog and having traffic more than thousand per day then you must choose Small instance which can handle that traffic very easily.
To create a new instance, access the AWS Management Console and click the EC2 tab:
- Choose an AMI in the classic instance wizard:
- I chose the Basic 64-bit Ubuntu Server Amazon Linux AMI.

- Instance details:
- Select the Instance Type you want to use. I chose Small (m5a.small).

- Create a new key pair.
- Enter a name for your key pair (i.e. crunchify) and download your key pair (i.e.
crunchify.pem
).
- Enter a name for your key pair (i.e. crunchify) and download your key pair (i.e.
- Select the quick start security group.
- Launch your instance.
3. SSH into your Instance
Once your instance setup is complete and it shows instance is running, you can ssh
into it.
- First of all, you need to identify the IP Address (public DNS) of your instance:
- Select the instance in the AWS Management Console.
- Look for the Public DNS in the instance description (bottom part of the screen).
Use that address (and a path to your .pem file) to ssh into your instance:
1 |
ssh ec2–user@ec2–50–17–15–27.compute–1.amazonaws.com –i ~/crunchify.pem |
If you are on windows system then you should use Putty for connect as SSH. You can connect with putty by following this article.
If you get an error message about your .pem file permissions being too open, chmod your .pem file as follows:
1 |
[ec2–user ~]$ chmod 600 ~/crunchify.pem |
In this tutorial you need to perform many shell commands and most of command require root access. So, to avoid this we will prefix these all command with sudo by switching user once for all by this command.
1 |
[ec2–user ~]$ sudo su |
4. Install the Apache Web Server to run PHP
To install the Apache Web Server, type in terminal:
1 2 3 4 |
[ec2–user ~]$ sudo yum –y install python–simplejson # Install PHP latest version [ec2–user ~]$ sudo yum update # System wide upgrade [ec2–user ~]$ sudo yum install –y default–jre # Install Java (just to be safe) [ec2–user ~]$ sudo yum install httpd # Install HTTPD server |
Start the Apache Web Server:
1 |
[ec2–user ~]$ service httpd start |
After setup, to test your Web Server, open a browser and access your web site:
1 |
http://ec2-50-17-15-27.compute-1.amazonaws.com |
(Use your actual public DNS name). You should see a standard Amazon place holder default page.
5. Install PHP to run WordPress
To install PHP, type in terminal:
1 |
[ec2–user ~]$ yum install php php–mysql |
After installing php successfully Restart the Apache Web Server:
1 |
[ec2–user ~]$ service httpd restart |
Create a page to test your PHP installation:
1 2 |
[ec2–user ~]$ cd /var/www/html [ec2–user ~]$ vi test.php |
- Type
i
to start the insert mode - Type
<?php phpinfo() ?>
- Type
:wq
to write the file and quit vi
Open a browser and access test.php to test your PHP installation:
1 |
http://ec2-50-17-15-27.compute-1.amazonaws.com/test.php |
(Use your public DNS name)
6. Install MySQL for adding database
To install MySQL, type:
1 |
[ec2–user ~]$ yum install mysql–server |
Start MySQL:
1 |
[ec2–user ~]$ service mysqld start |
Create your “blog” database:
1 |
[ec2–user ~]$ mysqladmin –u root create blog |
Secure your database:
1 |
[ec2–user ~]$ mysql_secure_installation |
Answer the wizard questions as follows:
- Enter current password for root: Press return for none
- Change Root Password: Y
- New Password: Enter your new password
- Remove anonymous user: Y
- Disallow root login remotely: Y
- Remove test database and access to it: Y
- Reload privilege tables now: Y
7. Install WordPress
To install WordPress, type:
1 2 |
[ec2–user ~]$ cd /var/www/html [ec2–user ~]$ wget http://wordpress.org/latest.tar.gz |
To uncompress tar.gz file type:
1 |
[ec2–user ~]$ tar –xzvf latest.tar.gzcd |
This will uncompress WordPress in its own WordPress
directory.
I like having WordPress in a separate directory, but would rather rename it to “blog” if you want to install it to subdomain like “http://your-site.com/blog”:
1 |
[ec2–user ~]$ mv wordpress blog |
otherwise move all files to parent folder by typing:
1 |
[ec2–user ~]$ mv *.* .. |
Create the WordPress wp-config.php file:
1 2 3 |
[ec2–user ~]$ cd blog [ec2–user ~]$ mv wp–config–sample.php wp–config.php [ec2–user ~]$ vi wp–config.php |
- Type
i
to start insert mode.
Modify the database connection parameters as follows:
1 2 3 4 |
define(‘DB_NAME’, ‘blog’); define(‘DB_USER’, ‘root’); define(‘DB_PASSWORD’, ‘YOUR_PASSWORD’); define(‘DB_HOST’, ‘localhost’); |
- Press
esc
one time then - Type
:wq
to write the file and quit vi
Open a Browser and access your blog:
1 |
http://ec2-50-17-15-27.compute-1.amazonaws.com/blog (Use your public DNS name). |
This should open the WordPress installation configuration process.
TIP: To allow WordPress to use permalinks
WordPress permalinks need to use Apache .htaccess files to work properly, but this is not enabled by default on Amazon Linux. Use this procedure to allow all overrides in the Apache document root.
Open the httpd.conf file with your favorite text editor (such as nano or vim). If you do not have a favorite text editor, nano is much easier for beginners to use.
1 |
[ec2–user wordpress]$ sudo vim /etc/httpd/conf/httpd.conf |
Find the section that starts with <Directory “/var/www/html
“>.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<Directory “/var/www/html”> # # Possible values for the Options directive are “None”, “All”, # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that “MultiViews” must be named *explicitly* — “Options All” # doesn’t give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.4/mod/core.html#options # for more information. # Options Indexes FollowSymLinks # # AllowOverride controls what directives may be placed in .htaccess files. # It can be “All”, “None”, or any combination of the keywords: # Options FileInfo AuthConfig Limit # AllowOverride None # # Controls who can get stuff from this server. # Require all granted </Directory> |
Change the AllowOverride None
line in the above section to read AllowOverride All
.
Note:
There are multiple AllowOverride
lines in this file; be sure you change the line in the <Directory "/var/www/html"
> section.
1 |
AllowOverride All |
- Save the file and exit your text editor.
8. Map IP Address and Domain Name
To use your blog in production, you will have to:
- Associate an IP address to your instance
- Map your domain name to that IP address
- To associate an IP address to your instance:
Steps:
- In the AWS Management Console, click Elastic IPs (left navigation bar)
- Click Allocate New Address, and confirm by clicking the “Yes, Allocate” button
- Right-click the newly allocated IP address and select “Associate” in the popup menu. Select the instance you just created and click “Yes, Associate”
- To map your domain name to your IP address, you will have to use the tools provided by your domain registrar.
- If you use GoDaddy, specify NS73.DOMAINCONTROL.COM and NS74.DOMAINCONTROL.COM as the name servers for your domain, and use the DNS Manager to modify the A record and point to your IP address.
- Once everything is configured and mapped correctly, access the General Settings in the WordPress management console and make sure the WordPress Address and Site Address are specified correctly using your domain name
Other Method: To change your WordPress site URL with the wp-cli
Note the old site URL and the new site URL for your instance. The old site URL is likely the public DNS name for your EC2 instance when you installed WordPress. The new site URL is the current public DNS name for your EC2 instance.
If you are not sure of your old site URL, you can use curl to find it with the following command.
1 |
[ec2–user ~]$ curl localhost | grep wp–content |
You should see references to your old public DNS name in the output, which will look like this (old site URL in red):
1 |
<script type=‘text/javascript’ src= http://ec2-50-17-15-27.compute-1.amazonaws.com/blog/wp-content/themes/twentyfifteen/js/functions.js?ver=20150330′></script> |
Download the wp-cli with the following command.
1 |
[ec2–user ~]$ curl –O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar |
Search and replace the old site URL in your WordPress installation with the following command. Substitute the old and new site URLs for your EC2 instance and the path to your WordPress installation (usually /var/www/html
or /var/www/html/blog
).
1 |
[ec2–user ~]$ php wp–cli.phar search–replace ‘old_site_url’ ‘new_site_url’ —path=/path/to/wordpress/installation —skip–columns=guid |
In a web browser, enter the new site URL of your WordPress blog to verify that the site is working properly again.
That’s it.
You have successfully created LAMP environment and installed WordPress on Amazon EC2. If you get any type of error or got stuck in some of task please let us know by commenting here.
We will try our best to provide solution for your problem.