Setup a domain on Amazon Linux with Apache websever

Here's how you create a virtual host on Apache2, on Amazon Linux, for a domain, or even a subdomain that you own. This guide was written and tested on an AWS EC2 instance with Amazon Linux. Let's assume to be the domain that requires setting up.

Setup a domain on Amazon Linux with Apache websever
Photo by Thomas Jensen / Unsplash

First we need to setup the directories and assign file+folder permissions - this will be done in the default webroot.

sudo mkdir -vp /var/www/vhosts/
sudo chown -R ec2-user:apache /var/www/vhosts/
mkdir -vp /var/www/vhosts/
sudo chown -R ec2-user:apache /var/www/vhosts/

Next, create the virtual host configuration file

sudo touch /etc/httpd/sites-enabled/
<VirtualHost *:80>
    ServerAlias *
    DocumentRoot /var/www/vhosts/
    RewriteEngine On
    # especially where AWS ALB is used
    RewriteCond %{HTTP:X-Forwarded-Proto} =http
    RewriteRule .* https://%{HTTP:Host}%{REQUEST_URI} [L,R=permanent]
    <Directory /var/www/vhosts/>
        Options -Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
        # revisit this config
        php_admin_value open_basedir  "/var/www/vhosts/"

    ErrorLog /var/www/vhosts/

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog /var/www/vhosts/ combined
Note: If you are using a Debian bases operating system, them switch commands from httpd to apache2

Everything has been configured, time to add some dummy files and content that will be served.

sudo touch /var/www/vhosts/
sudo printf '' > /var/www/vhosts/

Finally, test and restart the apache process

sudo service httpd restart