How to create exception to Apache Virtual hosts on AWS AMI/Ubuntu/Centos

The Apache web server is one of the easiest servers out there in terms of configuration and setting your websites up. It has its components distributed in different units controlled through their configuration files. This allows administrators to host multiple websites through the use of a matching mechanism.

Let’s see How to create exception to Apache Virtual hosts on AWS AMI/Ubuntu/Centos (Linux distributions)

Even if you are not looking to host multiple websites, In order to be able to use Microservice architecture, you will need to host your client end application and API separately. I proxy my API’s through Apache server for various reasons including scalability, cost, and security. That’s a discussion for another day though.

Today, I am sharing How to create an exception to Apache Virtual hosts on AWS AMI/Ubuntu/Centos (Linux distributions) .

Let’s say you wanted to send all requests to port 80(Http) or 443 (Https) to your client end application exception for a subdomain pointing to your API’s. Let’s call this backend.yourdomain.com. Requests from rest of the subdomains should hit your client end application. Obvious wildcard that comes to mind for this configuration is *.yourdomain.com , not to miss we speak of only the subdomains here.

Let’s see!


VirtualHost *:443
ServerName clientapp
ServerAlias *.yourdomainname.com
DocumentRoot /var/www/dist/
/VirtualHost

That’s good to redirect all requests to your client end application.

Now, comes the exception backend.yourdomain.com.


VirtualHost *:443
ServerName backend.yourdomain.com
SSLEngine on
SSLCertificateFile /home/user/backend.yourdomain.crt
SSLCertificateKeyFile /home/ec2-user/myserverbackend.yourdomain.key
ProxyRequests Off
ProxyPass / http://localhost:9999/
ProxyPassReverse / http://localhost:9999/
/VirtualHost

But, Apache vhosts would not care to go until the end of your file to see if you had something more specific than *.yourdomain.com. After all, backend.yourdomain.com also matches *.yourdomain.com.

How do we tell Apache server that we have an exception to the wildcard rule?

Ans: Place the exception before the wildcard rule.


VirtualHost *:443
ServerName backend.yourdomain.com
SSLEngine on
SSLCertificateFile /home/user/backend.yourdomain.crt
SSLCertificateKeyFile /home/ec2-user/myserverbackend.yourdomain.key
ProxyRequests Off
ProxyPass / http://localhost:9999/
ProxyPassReverse / http://localhost:9999/

ServerName clientapp
ServerAlias *.yourdomainname.com
DocumentRoot /var/www/dist/
/VirtualHost

Now, a request to port 443 is received by Apache, Apache checks the v-host entries in the order that matches and returns the one that matches the request.

NOTE: You cannot use wildcard operator in ServerName. Therefore use Server Alias to specify your wildcard entry in.


Leave a Reply

Your email address will not be published. Required fields are marked *