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 myapp.io 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/myapp.io/httpdocs
sudo chown -R ec2-user:apache /var/www/vhosts/myapp.io/httpdocs
mkdir -vp /var/www/vhosts/myapp.io/logs
sudo chown -R ec2-user:apache /var/www/vhosts/myapp.io/logs

Next, create the virtual host configuration file

sudo touch /etc/httpd/sites-enabled/myapp.io.conf
<VirtualHost *:80>
    ServerName myapp.io
    ServerAlias *.myapp.io
    DocumentRoot /var/www/vhosts/myapp.io/httpdocs/
    
    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/myapp.io/httpdocs/>
        Options -Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
        # revisit this config
        php_admin_value open_basedir  "/var/www/vhosts/myapp.io/httpdocs/:/tmp/:/"
    </Directory>

    ErrorLog /var/www/vhosts/myapp.io/logs/error.log

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

    CustomLog /var/www/vhosts/myapp.io/logs/access.log combined
</VirtualHost>
💡
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/myapp.io/httpdocs/index.html
sudo printf 'myapp.io' > /var/www/vhosts/myapp.io/httpdocs/index.html

Finally, test and restart the apache process

sudo service httpd restart