Linux VPS Apache And Virtual Hosts Setup

vim-html-code

This article contains the basic information to setup Mysql and Apache on an Ubuntu Linux VPS or Dedicated Server. This setup includes instructions on a virtual hosts setup with two main domains, one of which that has two subdomains. These instructions will likely need to be tailored to your local environment, but the basics are here.

If you haven’t yet setup your server, please read our Ubuntu VPS/Diedicated Server Setup article to help get you started.

These instructions should work on any linux distribution and the apache configuration information should be nearly universal. Some of the install lines will change depending on your linux distribution but for debian based distro’s these should work just fine.

1. Login in to your server

2. Installation of Apache

sudo aptitude install apache2 apache2.2-common apache2-mpm-prefork apache2-utils libexpat1 ssl-cert

sudo nano /etc/apache2/apache2.conf

add ServerName yourserver

sudo apache2ctl graceful (domain name error is now gone)

sudo nano /etc/apache2/sites-available/default

uncomment – RedirectMatch ^/$ /apache2-default/

sudo /etc/init.d/apache2 reload

3. Installation of PHP

sudo aptitude install libapache2-mod-php5 php5 php5-common php5-curl php5-dev php5-gd php5-imagick php5-mcrypt php5-memcache php5-mhash php5-mysql php5-pspell php5-snmp php5-sqlite php5-xmlrpc php5-xsl

sudo /etc/init.d/apache2 reload

4. Installation of MySQL

sudo aptitude install mysql-server and set server when asked “+++”

Now you have Apache, PHP, and MySQL installed and ready to be configured. Following is some basic Apache 2 Configurations for 2 Main Hosts, 1 with 2 Virtual Hosts. The file locations, etc. are all up to personal preference, but the following file locations are just as good as any. The apache settings in particular will need to be fine tuned for various situations, we use Drupal extensively – so these are sufficient for most small to medium sized Drupal (or other database driven CMS’s) sites.

5. Apache Configurations

sudo nano /etc/apache2/apache2.conf

Timeout 300 -> 100

MaxKeepAliveRequests 100 -> 200

KeepAliveTimout 15 -> 5

ServerTokens Full -> Prod

ServerSignature On -> Off

6. Apache2 Virtual Hosts Setup (using /srv/domain.com as document root – you can use anything else)

mkdir -p /srv/domainname.com/{public,private,logs,cgi-bin,backup}

mkdir -p /srv/sub.domainname.com/{public,private,logs,cgi-bin,backup}

Add the following to the bottom of /etc/apache2/apache2.conf

NameVirtualHost *:80

<IfModule mod_ssl.c>

NameVirtualHost *:443

</IfModule>

sudo nano /etc/apache2/sites-available/default

Remove NameVirtualHost and change to listen to port 80

So you should have:

<VirtualHost *:80>

Server….

at the top of your file

7. Setup First Virtual Host (replace “domain1″ with your hostname)

sudo nano /etc/apache2/sites-available/domain1.com

Should look generally like:

++++Start File++++

# Place any notes or comments you have here

# It will make any customization easier to understand in the weeks to come

# domain: domain1.com

# public: /srv/domain1.com/

# Admin email, Server Name (domain name) and any aliases

ServerAdmin webmaster@domain1.com

ServerName domain1.com

ServerAlias www.domain1.com

# Index file and Document Root (where the public files are located)

DirectoryIndex index.html

DocumentRoot /srv/domain1.com/public

# Custom log file locations

LogLevel warn

ErrorLog /srv/domain1.com/logs/error.log

CustomLog /srv/domain1.com/logs/access.log combined
++++End File++++

8. Setup Second Virtual Host (which also a domain alias and two independent Subdomains – replace hostname2., hostname2alias, sub1, and sub2 with your hostname, your top level domain alias, subdomain1 name, and subdomain2 name respectively)

sudo nano /etc/apache2/sites-available/hostname2.com

Should look generally like:

++++Start File++++

# Place any notes or comments you have here

# It will make any customisation easier to understand in the weeks to come

# domain: hostname2.com

# public: /srv/hostname2.com/

# Admin email, Server Name (domain name) and any aliases

ServerAdmin webmaster@hostname2.com

ServerName hostname2.com

ServerAlias www.hostname2.com

UseCanonicalName Off

ServerAlias hostname2alias.com

ServerAlias www.hostname2alias.com

# Index file and Document Root (where the public files are located)

DirectoryIndex index.html

DocumentRoot /srv/hostname2.com/public
Options Indexes FollowSymLinks +Includes

AllowOverride All

Order allow,deny

allow from all

# Custom log file locations

LogLevel warn

ErrorLog /srv/hostname2.com/logs/error.log

CustomLog /srv/hostname2.com/logs/access.log combined

ScriptAlias /cgi-bin/ /srv/hostname2.com/cgi-bin/

# Admin email, Server Name (domain name) and any aliases

ServerName sub1.hostname2.com

ServerAdmin webmaster@hostname2.com

ServerAlias www.sub1.hostname2.com

# Index file and Document Root (where the public files are located)

DirectoryIndex index.html

DocumentRoot /srv/hostname2.com/subdomains/sub1/public

# Custom log file locations

LogLevel warn

ErrorLog /srv/hostname2.com/subdomains/sub1/logs/error.log

CustomLog /srv/hostname2.com/subdomains/sub1/logs/access.log combined

# Admin email, Server Name (domain name) and any aliases

ServerAdmin webmaster@hostname2.com

ServerName sub2.hostname2.com

ServerAlias www.sub2.hostname2.com

ServerAlias sub2.hostname2alias.com

ServerAlias www.sub2.hostname2alias.com

# Index file and Document Root (where the public files are located)

DirectoryIndex index.html

DocumentRoot /srv/hostname2.com/subdomains/sub2/public

# Custom log file locations

LogLevel warn

ErrorLog /srv/hostname2.com/subdomains/sub2/logs/error.log

CustomLog /srv/hostname2.com/subdomains/sub2/logs/access.log combined
++++End File++++

Now you can enable your sites – this command simply makes a symbolic link from sites-enabled to the configuration files you just setup in sites-available.

9. Enable Sites

sudo a2ensite domain1.com

sudo a2ensite hostname2.com

Then Restart Apache:

sudo /etc/init.d/apache2 reload

The next section involves enabling the apache module mod_rewrite (and any other modules you require for your particular setup)

10. Enable mod_rewrite

sudo a2enmod rewrite

sudo /etc/init.d/apache2 force-reload

Install Or Move Drupal To A Linux VPS

vim2-html

This article covers some basic steps to move an existing installation of Drupal or to create a new installation of Drupal on a linux VPS – in this case one running Ubuntu hosted with Linode. These instructions assume some configurations that we have performed in previous articles, so your individual configuration may vary.

The related articles are our Ubuntu Setup on a Linode VPS, and our PHP, Mysql, Apache Setup on Ubuntu articles.

Your particular situation may vary, but these general steps are common to most situations. These steps are related more to creating databases, moving data around, etc. and do not cover the installation of Drupal in any depth. The Drupal guidebooks have detailed information on this, and the procedure is fairly straightforward (i.e. create the database, copy the files to your location, and edit the settings file with your db username and password).

1. Setup The MySQL Database For Your Site
sudo mysql -u root -p
CREATE DATABASE name;
GRANT ALL PRIVILEGES ON dbname.* TO "dbuser" IDENTIFIED BY "dbpass";
FLUSH PRIVILEGES;

2. Copy Your Database Files (if you are moving an existing site, otherwise the empty database is fine) and your Drupal files to your site:
scp -r -P yoursshport /home/myaccount/mysites/site1 username@yourip:~/webfiles

scp -r -P 30101 /home/myaccount/mysites/site1.sql username@yourip:~/webfiles

3. In case you don’t already have a database dump from a previous host and just for reference. Here is how you peform and database backup and restore for Drupal (and any other database)
mysqldump -u username -p database > file.sql
mysql -u username -p database < file.sql

4. Connect to your server and upload the database file you just copied over:

ssh -P yoursshport yourusername@yourip
mysql -u username -p databasename < /home/websites/site1.sql

5. Copy your web files to the appropriate directory:
cp -r /webfiles* /srv/hostname.com/public

6. Final Apache Changes for Drupal .htaccess to work
In /etc/apache2/domainname.com.conf make sure these sections match:

  <Directory /srv/domainname/public/>
                Options Indexes FollowSymLinks +Includes
                AllowOverride All
                Order allow,deny
                allow from all
  </Directory>

Drupal and other CMS’s require cron jobs to perform a range of maintenance tasks. The following sets up the crontab to run drupal cron application to perform the necessary system updated. The following lines will run it every 6 hours at 3 minutes past the hour. You can modify this according to your needs (hourly, daily, etc.).

7. Drupal Cron Setup for domain1

  sudo crontab -e
  3 */6 * * * /usr/bin/wget -O – -q http://domain1.com/cron.php
  sudo crontab -l

 

Installation of Ubuntu Server on a Linode VPS With Basic Security Setup

vim-html-code

This article will cover the installation of Ubuntu Linux (7.10) on a Linode VPS with startup management tasks, ip tables firewalling, and basic server security techniques. This article assumes you are using a linux machine locally as well, but for the majority you are using a simple ssh client, web browser, and an editor – so adapt these to your local configuration.

Note: While these instructions are for a VPS within Linode, they are essentially the same for any hosting company/distribution with the exception of some differences between debian based linux systems and redhat based ones (apt-get vs. yum, etc.).

If you don’t have a dedicated server, or a VPS, we often recommend Linode as your hosting company. Their support is quite good and their offerings are well provisioned. There are a vast number of hosting companies, but in our opinion Linode is one of the best.

1. Install Ubuntu 7.10 on linode (through the dashboard system, very easy…)

2. While waiting clear your local ssh known_hosts (if necessary, reinstall, etc.)

nano ~/.ssh/known_hosts  (remove all references to vps ip)

3. ssh in as your linode account to lish on your host and then login to your linode as root or for non linode customers (or linode users alternatively)

ssh root@yourip   – then change your pass

passwd

4. Create a new account (so you are not logging in as root)

adduser username

5. Grant new user su privileges

visudo  (at the end of the file add:)

username ALL=(ALL) ALL

6. Login & Set Hostname:

/bin/hostname yourhostname.com

echo yourhostname.com > /etc/hostname

This next section will setup SSH encryption between your local computer(s) and your server. These steps essentially disallow any logins besides those coming from a machine with your SSH key. If you need to travel from computer to computer you will need to perform these steps on all the computers you use. On linode (and other hosts) you can always login through the web interface provided through the dashboard management system.

Set up correctly, these steps stop any number of security attacks from randomly guessing the root password, etc. It enables a fairly high level of initial security.

7. SSH Keygen public/private key (stop logins with just a password)

On Local Machine:

mkdir ~/.ssh

ssh-keygen -t rsa (this makes 2 files – id_rsa.pub (public key) – id_rsa (private key)

Copy public key to Linode:

scp ~/.ssh/id_rsa.pub username@ip:/home/username/

On Your Linode VPS:

mkdir /home/username/.ssh

mv /home/username/id_rsa.pub /home/username/.ssh/authorized_keys

Permissions:

chown -R username:usergroup /home/username/.ssh

chmod 700 /home/username/.ssh

chmod 600 /home/username/.ssh/authorized_keys

8. SSH config

nano /etc/ssh/sshd_config

Change SSH Port to something (i.e. 30100, 30211, anything high really)

Protocol 2

PermitRootLogin no

Unpound AuthorizedKeyFiles…

PasswordAuthentication no

X11Forwarding no

UsePAM no

UseDNS no

AllUsers username

This next section runs through a basic configuration of the IP Tables Firewall system. There are many other helper applications for establishing a firewall on a linux machine, but doing it by hand helps people to understand the concepts involved.

9. Firewall setup (iptables)

iptables-save > /etc/iptables.up.rules

iptables -L

nano /etc/iptables.test.rules config below:

Below is a basic IP Tables Configuration File that locks nearly everything down. As you add services you can open required ports for traffic, but for most people this configuration will meet all their needs.

++++Begin File++++

*filter

#  Allows all loopback (lo0) traffic and drop all traffic to 127/8 that doesn’t use lo0

-A INPUT -i lo -j ACCEPT

-A INPUT -i ! lo -d 127.0.0.0/8 -j REJECT

#  Accepts all established inbound connections

-A INPUT -m state –state ESTABLISHED,RELATED -j ACCEPT

#  Allows all outbound traffic

#  You can modify this to only allow certain traffic

-A OUTPUT -j ACCEPT

# Allows HTTP and HTTPS connections from anywhere (the normal ports for websites)

-A INPUT -p tcp –dport 80 -j ACCEPT

-A INPUT -p tcp –dport 443 -j ACCEPT

#  Allows SSH connections

#

# THE -dport NUMBER IS THE SAME ONE YOU SET UP IN THE SSHD_CONFIG FILE

#

-A INPUT -p tcp -m state –state NEW –dport 30000 -j ACCEPT

# Allow ping

-A INPUT -p icmp -m icmp –icmp-type 8 -j ACCEPT

# log iptables denied calls

-A INPUT -m limit –limit 5/min -j LOG –log-prefix “iptables denied: ” –log-level 7

# Reject all other inbound – default deny unless explicitly allowed policy

-A INPUT -j REJECT

-A FORWARD -j REJECT

COMMIT

++++End File++++

10. Store new IP Tables Information

iptables-restore > /etc/iptables.test.rules

iptables -L

iptables-save > /etc/iptables.up.rules

11. Ensure iptables loads at startup

nano /etc/network/interfaces

after iface…

pre-up iptables-restore > /etc/iptables.up.rules

12. Test connections (don’t logout yet!)

/etc/init.d/ssh reload

From a new local terminal test ssh:

ssh -P portyouset username@yourip

13. Set Locale

sudo locale-gen en_US.UTF-8

sudo /usr/sbin/update-locale LANG=en_US.UTF-8

14. Reboot and login as your newuser via the ssh command:

ssh -P portyouset username@yourip

Now that you have established your ssh keys and a connection and locked down the majority of the open ports on the computer you can setup your local environment. These can be changed according to your needs – just a basic setup that many people will find satisfactory.

15. Configure your local environment

nano ~/.bashrc

export PS1='[�33[0;32m]h[�33[0;36m] w[�33[00m]: ‘

alias dir=”ls -lartF”

alias free=”free -m”

alias update=”sudo aptitude update”

alias install=”sudo aptitude install”

alias upgrade=”sudo aptitude safe-upgrade”

alias remove=”sudo aptitude remove”

16. Get Your Ubuntu Server up to date

sudo nano /etc/apt/sources.list

enable all repositories

sudo aptitude update

sudo aptitude safe-upgrade

sudo aptitude full-upgrade

Finally install the build essentials package which has the tools necessary to install apache, mysql, and other applications you are going to install on your server.

17. Install build essentials

sudo aptitude install build-essential

Install PHPMyAdmin On A Linux VPS

vim2-html

This article covers the basics of setting of PHPMyAdmin to manage your MySQL databases on your Ubuntu Linux machine. These instructions will also work for a variety of other linux distributions as well. This is part of our series on setting up a Linode VPS with a fully working PHP, Apache, MySQL setup with multiple domains.

The following articles may be of interest to you:
Basic Linode VPS Setup
PHP, Apache, MySQL Setup on Ubuntu
Drupal Setup on Ubuntu

1. PhpMyAdmin Setup
sudo aptitude install phpmyadmin
This sets up phpmyadmin at your default server /phpmyadmin
PhpMyAdmin uses the following components/locations by default:

/usr/share/phpmyadmin
    /etc/apache2/conf.d/phpmyadmin.conf
    /etc/phpmyadmin

Below is a minor security change to the location of phpmyadmin to offset hackers who try to break in via the interface by going to yoursite.com/phpmyadmin . This isn’t all that strong, but every little thing helps.

2. Minor PhpMyAdmin Security Change
sudo nano /etc/apache2/conf.d/phpmyadmin.conf
Change Alias /myphpalias to /usr/share/phpmyadmin
Then available at http://domainname/myphpalias instead of phpmyadmin