How to block direct IP access from Apache Web Server on AWS EC2

Introduction

While I was running the site and looking at the access history, I found a history of accessing it by directly entering the IP address. Most users access by entering a domain name, and if they access with an IP address, it can be considered that there are few if not it bots. Of course, in my case, AWS uses elastic IP as a fixed IP. Perhaps because it is a fixed IP, there are not a few direct IP address accesses, and I would like to explain how to block direct IP access from the Apache Web Server of AWS EC2 currently in use.

How to get the public IP address of AWS EC2

First, you need to know the public IP address of AWS EC2. You can access the AWS EC2 Console with a web browser and get an IP address, but if it is not a fixed IP, you may have to use another method. Here, the AWS EC2 instance metadata service was used.

The method is simple. If you enter the following command at the terminal of the EC2 instance, the public IP address of the instance is output. It is said that the commands used here are only available on EC2 instances.

curl -s http://169.254.169.254/latest/meta-data/public-ipv4

Configuration Apache Web Server

This article is based on the Debian family of Linux distributions such as Ubuntu Server, and assumes that basic settings such as the Apache Web Server installation have been completed.

The basic HTTP protocol (port 80) adds the following to the site configuration file. It should be written after another site. If you want to apply to the HTTPS protocol (port 443), you can add it.

<VirtualHost *:80>
	ServerName xxx.xxx.xxx.xxx
	<Location />
		Order deny,allow
		Deny from all
	</Location>
</VirtualHost>

Configuring Environment Variables

If you are currently using a fixed IP, the above method will be sufficient. If not, there will be a hassle of changing the setting every time the IP address changes. To reduce this hassle, we introduce a method of configuring IP addresses in environment variables. For reference, this method only works with AWS EC2.

The method is simple. The value of the command to get the IP in the instance described above may be saved as an environment variable. Add the following to the /etc/apache2/envvars (by Ubuntu) file.

export PUBLIC_IP=$(curl -s http://169.254.169.254/latest/meta-data/public-ipv4)

And change the site configures described above as follows.

<VirtualHost *:80>
	ServerName ${PUBLIC_IP}
	<Location />
		Order deny,allow
		Deny from all
	</Location>
</VirtualHost>

If you finish configuration and restart Apache Web Server, you will see a 403 Forbidden error message when you directly connect to the IP address.

Conclusion

we’ve looked at how to block direct access to IP addresses. While managing the WordPress blog, there were many strange history in the access history. I hope this method will help you manage the web server even a little.

Leave a Reply