Categories
Apache

Apache Virtual Hosts

Configuring Apache Standalone and XAMPP

When running a server such as Apache standalone or as part of XAMPP, this server is configured as the single listener to at least one network port. For example, by default, Apache will listen to ports 80 and 443, the HTTP and HTTPS default ports. No other server can be listeners to the same ports on the same computer. This means that if you need to host two different Web applications on the same server computer, then you will nut be able to use two different servers.

Apache has a mechanism to cater to this type of situation: virtual hosts. By this mechanism, we can configure multiple Web applications in different folders and on different domain names (or subdomains).

To set up virtual hosts on Apache you will only need to follow 3 steps:

  1. Store the Web application to host in a location accessible to your Apache instance.
  2. Edit the hosts file to add the wanted domains/subdomains.
  3. Add the virtual host configurations to Apache configuration files.

1. Store the Web Application

Place the Web application in the file system by creating a folder and placing your code there. I recommend placing your Web application under the xampp folder, in a subfolder created by your git client – because your Web application code is managed in a git repository, right?

For our example, we will add 2 Web applications in the following folders under the xampp folder: SocialApp and Marketplace.

Make a note of where you have stored your Web applications.

2. Edit the hosts File

Depending on your operating system, you may find the hosts file in one of a few places (check for your exact OS):

  1. In the Windows OS, it is typically located under C:\Windows\System32\drivers\etc\hosts
  2. In Linux distributions, you may find it at /etc/hosts
  3. In MacOS, you may find it at /private/etc/hosts

To edit this file, use an account with administrative privileges in your OS. Under Windows, you may open a text editor such as notepad as administrator by right clicking the application icon and selecting “Open as administrator”. Under Linux and MacOS, you should invoke your editor with sudo, for example.

In our example we will route from 2 subdomains: socialapp.localhost and marketplace.localhost. To perform this change, we will add the 2 following lines to the hosts file:

  1. 127.0.0.1    socialapp.localhost
  2. 127.0.0.1    marketplace.localhost

Thanks to those 2 lines, requests to these addresses will be forwarded to 127.0.0.1, the loopback IP address. General information on the hosts file may be found on Wikipedia.

3. Add the Virtual Host Configurations

Apache Configuration in XAMPP

If you are using XAMPP installed for example in the c:\xampp folder, then open c:\xampp\apache\conf\extra\httpd-vhosts.conf file and add the following at the end of the file:

  1. <virtualhost *:80="">
  2.     ServerAdmin webmaster@email.com
  3.     DocumentRoot "C:/xampp/socialapp"
  4.     ServerName socialapp.localhost
  5.     ErrorLog "socialapp.log"
  6.     CustomLog "socialapp-access.log" common
  7.     <directory "C:/xampp/socialapp">
  8.         AllowOverride All
  9.         Require all granted
  10.     </directory>
  11. </virtualhost>
  12.  
  13. <virtualhost *:80="">
  14.     ServerAdmin webmaster@email.com
  15.     DocumentRoot "C:/xampp/marketplace"
  16.     ServerName marketplace.localhost
  17.     ErrorLog "marketplace.log"
  18.     CustomLog "marketplace-access.log" common
  19.     <directory "C:/xampp/marketplace">
  20.         AllowOverride All
  21.         Require all granted
  22.     </directory>
  23. </virtualhost>
  24.  
  25. <virtualhost *:80="">
  26.     ServerAdmin webmaster@email.com
  27.     DocumentRoot "C:/xampp/htdocs"
  28.     ServerName localhost
  29.     ErrorLog "localhost.log"
  30.     CustomLog "localhost-access.log" common
  31.     <directory "C:/xampp/htdocs">
  32.         AllowOverride All
  33.         Require all granted
  34.     </directory>
  35. </virtualhost>

Notice the entry for localhost that is at the end. Without this entry, access to the htdocs document root for localhost may be broken, even if it is defined elsewhere. Not all instructions are required for this example to be functional. The instructions have the following use:

  • ServerAdmin: (Optional) set the value of $_SERVER[‘SERVER_ADMIN’]
  • DocumentRoot: specify the root folder for this Web application
  • ServerName: specify the domain name for this Web application
  • ErrorLog: (Optional) set the file where errors are logged for this Web application
  • CustomLog: (Optional) set the file where all non-error events are logged for this Web application. The common format will be used to write messages.
  • <Directory tag>: To set the correct root folder access parameters, repeat the document root here.
  • AllowOverride All: Allow all directived in .htaccess
  • Require all granted: All IP addresses may access the Web application

Once these changes are made, Apache must be restarted for changes to take effect. First test the configuration by running

  1. \xampp\apache\bin\httpd -t

Once the output for this reads “Syntax OK”, you are ready to restart Apache. For more information on which options to select and for which reasons, you may consult Apache documentation.

Standalone Apache Configuration

If instead of using XAMPP, you are using Apache standalone, you should create one configuration file per virtual host and place these in the /etc/apache2/sites-available folder. For our example, we will build 2 files.

The first file is /etc/apache2/sites-available/socialapp.conf:

  1. <virtualhost *:80="">
  2.     ServerAdmin webmaster@email.com
  3.     DocumentRoot "C:/xampp/socialapp"
  4.     ServerName socialapp.localhost
  5.     ErrorLog "socialapp.log"
  6.     CustomLog "socialapp-access.log" common
  7.     <directory "C:/xampp/socialapp">
  8.         AllowOverride All
  9.         Require all granted
  10.     </directory>
  11. </virtualhost>

The second file is /etc/apache2/sites-available/marketplace.conf:

  1. <virtualhost *:80="">
  2.     ServerAdmin webmaster@email.com
  3.     DocumentRoot "C:/xampp/marketplace"
  4.     ServerName marketplace.localhost
  5.     ErrorLog "marketplace.log"
  6.     CustomLog "marketplace-access.log" common
  7.     <directory "C:/xampp/marketplace">
  8.         AllowOverride All
  9.         Require all granted
  10.     </directory>
  11. </virtualhost>

To enable configuration changes, run the following commands at yout command line:

  1. sudo a2ensite socialapp
  2. sudo a2ensite marketplace

The above creates the symbolic links between the /etc/apache2/sites-enabled/ folder and the /etc/apache2/sites-available/ configuration files. To ensure the Apache has read all its configuration files, we reload it as follows:

  1. sudo /etc/init.d/apache2 reload

Conclusion

The above instructions apply to many cases but not all installations were considered. If you have a common installation that is not covered in this post, let me know in the comments below.

Categories
Apache PHP

Bootstrapping Web Applications with .htaccess

The .htaccess file allows us to perform several security and modification operations for our Web applications to work as intended.

Let’s consider the example .htaccess file as follows:

Options -Indexes
Options -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

Options

Options are set mainly to change folder access. We set these options on or off respectively with + and .

Indexes

When allowed, Indexes allows the listing of all files in a folder by accessing this through a request. Therefore, is is especially important to turn this option off (with -) to not reveal the contents of your folders. This will make it harder to exploit your system for evil intents.

MultiViews

When turned on, MultiViews may cause substitute files to be read when others are required that incompletely match the name of those present on the server. In the case of an MVC application, we wish to completely route the application based on requests not matching the files in the system, and furthermore, we wish to still allow resources to be directly loaded by the browser. We must turn off this option.

URL Rewriting

One useful thing Apache can do to make your MVC Web application work well if to rewrite URLs in such a way that the URL becomes a parameter for a PHP application entry point.

RewriteEngine On

Before any URL rewriting happens, we must turn on the rewriting engine.

RewriteBase

The RewriteBase directive specifies the URL prefix to be used for per-directory (htaccess) RewriteRule directives that substitute a relative path. Here, we wish to call the index.php file in the Web server document root.

RewriteCond directive

The RewriteCond directive defines a rule condition. One or more RewriteCond can precede a RewriteRule directive. The following RewriteRule is then only used if the current state of the URI matches its pattern, and if all these conditions are met.

REQUEST_FILENAME is the full local filesystem path to the file or script matching the request.

-f: Is regular file. (alternatively !-f is NOT regular file.)
Treats the TestString as a pathname and tests whether or not it exists, and is a regular file.

-d: Is directory. (alternatively !-d is NOT directory.)
Treats the TestString as a pathname and tests whether or not it exists, and is a directory.

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

So the above sets conditions that the requested file is neither a file or folder that exists. This will allow the browser to fetch stylesheets, libraries, etc. from the resources without having to be routed by the MVC application.

RewriteRule

This sets the rule that will be run once the conditions are met. In the above example

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

the rule matches the incoming requested URL, except the server address, and sends this URL to index.php, through the URL query string parameter. Any other query string parameters are added by virtue of the QSA (Query String Append) flag. The L flag ensures that no further rules are applied to this request if this rule is run.

RewriteRule flags

For more information on applicable RewriteRule flags, consult the documentation at https://httpd.apache.org/docs/2.4/rewrite/flags.html.

Taking security one step further

One more .htaccess file is needed in the app folder of your MVC application (or wherever your application stores its code which should not be accesses directly through Http requests). The file is as follows:

Options -Indexes
Deny from all

This will not allow users to list contents of any folder as well as disallow direct access to any file through external requests. Only your internal code will be able to include, require and run this code.

Completing the application

Consider the above .htaccess file is in the Apache server document root with the following index.php file:

<?php
  var_dump($_GET);
?>

Then, for any request with characters after the / following the hostname, e.g., https://cstutoring.ca/Hello/Alice, the characters would be displayed in an output of the following nature:

 array(1) { ["url"]=> string(11) "Hello/Alice" } 

We can now use the ‘url’ value to enable routing within the MVC application.