Top

A Linux User Reference

Search tips
  • search ignores words that are less than 4 characters in length
  • searches are case insensitve
  • if a search does not return anything try it in Boolean mode then Query expansion mode by checking the appropriate radio button e.g. searching for 'cron' in just the Administration category returns nothing - presumably because the 50% threshold is reached. Boolean mode ignores this threshold so a search for 'cron' returns several hits
  • in Boolean mode preceding a word with a '+' means the result must include that word, a '-' means it must not
  • in Boolean mode '+crontab -anacron' means match articles about crontab that DO NOT mention anacron
  • to match a phrase e.g. 'manage system' check the Boolean mode radio button and enclose the phrase in quotes "some phrase ..."
  • in Query expansion mode the search context is expanded beyond the keywords you entered - relevancy of hits may well be degraded

NETWORK APPLICATIONS

Apache Web Server

  • Link to project documents
  • Installing from source
    • Versions: 1.3.x, 2.2.x
    • Assumes source tarball has been downloaded and unpacked
    • Always read the README

    Configure and install - at it's simplest

    $ ./configure
    $ make
    # make install            (as root)
    

    Check your distro's documentation along with apache.org's documentation.

    Apache modules

    See sectionNetworked Application → Apache Web Server modules for more info. on modules.

    Enable 'headers proxy ssl dav cgi rewrite' modules (except mod_so.c and mod_http.c) as DSOs

    $ ./configure --prefix=/opt/apache --enable-so --enable-http \
    --enable-mods-shared="headers proxy ssl dav cgi rewrite"
    

    Common compile time options

     --prefix=pref              Where to install. default: /usr/local/apache
     --enable-so                Enable loading of DSOs - statically linked i.e. built into binary
     --enable-headers
     --enable-proxy             Run as a proxy. SQUID is better.
     --enable-ssl               Enable secure socket layer encryption
     --enable-http              Enable http protocol - statically linked
     --enable-dav               Allow 3rd. Party software to edit web pages directly
     --enable-cgi               Enable Common Gateway Interface scripts
     --enable-rewrite           Ability to apply regular expression based rules to 
                                redirect HTTP requests
    
  • Apache2 directory structure

    Debian - /etc/apache2/

    $ tree -afF -L 1 .
    |-- ./apache2.conf              (Main configuration file
    |-- ./conf.d/
    |-- ./envvars                   (Environment variables)
    |-- ./httpd.conf                (User - additional - configurations)
    |-- ./mods-available/
    |-- ./mods-enabled/             (Enabled modules plus their configurations)
    |-- ./ports.conf                (Ports to listen on)
    |-- ./sites-available/
    `-- ./sites-enabled/            (Virtual host(s) configuration(s))
    

    Non debian

    /etc/apache/                    (Default server configuration files)
    
    (or)
    
    /etc/httpd/
    | -- ./conf/httpd.conf                            (General server attributes, 
                                                       port number, user to run as ...)
    | -- ./conf.d/
    | -- ./logs -> ../../var/log/httpd                (Access_log, error_log ...)
    | -- ./modules -> ../../usr/lib64/httpd/modules   (DSOs)
    | -- ./run -> ../../var/run                       (httpd.pid)
    | -- ./access.conf                                (Base cases for access)
    | -- ./srm.conf                                   (Contents of ... below)
    

    /etc/httpd/srm.conf

    # This is the default file for the ResourceConfig directive in httpd.conf.
    # It is processed after httpd.conf but before access.conf.
    #
    # To avoid confusion, it is recommended that you put all of your
    # Apache server directives into the httpd.conf file and leave this
    # one essentially empty.
    

    Server configuration file

    The main configuration may be in one of several locations - /etc/apache/, /etc/httpd/, /etc/apache2/ ... Later versions are backwards compatible so they may well reference, include earlier file names.

    File/Directory Contents
    /etc/httpd/conf/httpd.conf Main configuration file
    /etc/httpd/conf.d/* Configuration directory
    /etc/apache2/apache2.conf Main configuration file
    /etc/apache2/conf.d/* Configuration directory
  • Basic configuration example
    /etc/httpd/httpd.conf
    serverRoot "/etc/httpd"          # NO slash at the end of the directory path
    maxKeepAliveRequests 100         # Max num. of requests during a persistent connection.
                                     # 0 = unlimited, 'high' => maximum performance.
    listen 127.0.0.1:80              # Address to listen on.  Stops Apache binding to all 
                                     # interfaces.
    include conf.d/*.conf            # Include config files in /etc/httpd/conf.d.
    serverAdmin root@localhost       # Address to e-mail server generated mails, appears on
                                     # some pages, error docs.
    ServerName www.example.com:80    # Server Name and port, often determined automatically.
    useCanonicalName Off             # 'Off' use hostname and port supplied by client for 
                                     # self-referencing URLs.
                                     # 'On'  use value supplied by ServerName directive.
    documentRoot "/var/www/html"     # Root dir from which all documents are served.
    errorLog logs/error_log          # Location and name of error log file.  If defined in
                                     # a <VirtualHost> container the virtual host 
                                     # will log to that one, if not then this one.
    logLevel warn                    # Number (and type) of messages to log to error log.
                                     # Values include: 
                                     # debug, info, notice, warn, error, crit, alert, emerg
    
  • Basic configuration example
    /etc/apache2/apache2.conf

    This file is well documented so you are best off viewing it on your own server - in the event that you do not have access to one here is an oldish one with a few extra notes in it.

    ### Section 1:
    ### Global Environment
    ServerRoot "/etc/apache2"                 # ServerRoot: The top of the directory tree under which the
                                              # server's configuration, error, and log files are kept.
    PidFile ${APACHE_PID_FILE}                # This needs to be set in /etc/apache2/envvars
    Timeout 300                               # The number of seconds before receives and sends time out.
    KeepAlive On                              # allow (or not) persistent connections (more than one
                                              # request per  connection). Set to "Off" to deactivate.
    MaxKeepAliveRequests 100                  # Max number of requests to allow during a
                                              # persistent connection. 0 = unlimited.  High for max perf
    KeepAliveTimeout 15                       # Number of seconds to wait for the next request
                                              # from the same client on the same connection.
    <IfModule mpm_prefork_module>             # prefork MPM
        StartServers          5               # Number of server processes to start
        MinSpareServers       5               # Minimum number of server processes which are kept spare
        MaxSpareServers      10               # Maximum number of server processes which are kept spare
        MaxClients          150               # Maximum number of server processes allowed to start
        MaxRequestsPerChild   0               # Maximum number of requests a server process serves
    </IfModule>
    <IfModule mpm_worker_module>              # worker MPM
        StartServers          2               # Initial number of server processes to start
        MaxClients          150               # Maximum number of simultaneous client connections
        MinSpareThreads      25               # Minimum number of worker threads which are kept spare
        MaxSpareThreads      75               # Maximum number of worker threads which are kept spare
        ThreadsPerChild      25               # Constant number of worker threads in each server process
        MaxRequestsPerChild   0               # Maximum number of requests a server process serves
    </IfModule>
    User ${APACHE_RUN_USER}                   # These need to be set in /etc/apache2/envvars
    Group ${APACHE_RUN_GROUP}
    AccessFileName .htaccess                  # The name of the file to look for in each directory
                                              # for additional configuration directives
    <Files ~ "^\.ht">                         # The following lines prevent .htaccess and .htpasswd 
        Order allow,deny                      # files from being viewed by web clients
        Deny from all
    </Files>
    HostnameLookups Off                       # Log the names of clients or just their IP addresses
    ErrorLog /var/log/apache2/error.log       # The location of the error log file. If not specified in a
                                              # <VitualHost> logged here also
    LogLevel warn                             # Control the number of messages logged to the error_log
                                              # Possible values: 
                                              # debug, info, notice, warn, error, crit, alert, emerg
    Include /etc/apache2/mods-enabled/*.load  # Include module configuration: links to mods-available
    Include /etc/apache2/mods-enabled/*.conf
    /etc/apache2/mods-enabled/dir.conf
    <IfModule mod_dir.c>
        DirectoryIndex index.php index.cgi index.pl index.php index.xhtml index.htm
    </IfModule>
    
    ### equivalent to old Section 2:
    ### Main server configuration
    Include /etc/apache2/httpd.conf           # Include all the user configurations:
    Include /etc/apache2/ports.conf           # Include ports listing
    Listen 80
    <IfModule mod_ssl.c>
        Listen 443
    </IfModule>
    
    # The following directives define some format nicknames for use with a
    # CustomLog directive (see below).
    # If behind a reverse proxy may wish to change %h to %{X-Forwarded-For}i
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common
                                              # IP address of the client (%h)
                                              # RFC 1413 identity determined by identd (%l)
                                              # userid of person requesting (%u)
                                              # time server finished serving request (%t)
                                              # request line of user (%r)
                                              # status code servers sent to client (%s)
                                              # size of object returned (%b).
    
    # Configures what is returned as the Server HTTP response Header
    # Default is 'Full' => OS-Type and compiled in modules
    # Set to one of:  Full | OS | Minor | Minimal | Major | Prod
    # where Full conveys the most information and Prod the least
    ServerTokens Full
    
    # Optionally add a line containing the server version and virtual
    # host name to server-generated pages
    # Set to On | Off | Email, "EMail" to also include a
    # mailto: link to the ServerAdmin
    ServerSignature On
    
    Include /etc/apache2/conf.d/              # Include generic snippets of statements
    
    ### equivalent to old Section 3:
    ### Virtual Hosts
    Include /etc/apache2/sites-enabled/       # Include the virtual host configurations
    

    Virtual hosts (debian) - /etc/apache2/sites-enabled

    $ ls sites-enabled
    000-default  blog  c5  gallery  linref  nixref  skeleton
    

    Basic virtual host file - /etc/apache2/sites-available/nixref

    <VirtualHost *:80>
            ServerName nixref
        DocumentRoot /home/markw049/www/nixref
    
        <Directory />
            Options FollowSymLinks
            AllowOverride None
        </Directory>
    
        <Directory /home/markw049/www/nixref/>
            Options FollowSymLinks MultiViews
            # AllowOverride None
                    # so .htaccess rules can rewrite a url
            AllowOverride All
            Order allow,deny
            allow from all
        </Directory>
    
    </VirtualHost>
    
  • Managing the server
    /usr/sbin/httpd, apache2

    The server daemon can be managed directly via the 'httpd' command/program or via a front-end ('apachectl', 'apache2', 'apache2ctl').

    Apache server daemon

    httpd [options]
    
    Options:
     -D name               Define a name for use in <IfDefine name> directives
     -d directory          Specify an alternate initial ServerRoot
     -f file               Specify an alternate ServerConfigFile
     -C "directive"        Process directive before reading config files
     -c "directive"        Process directive after reading config files
     -e level              Show startup errors of level (see LogLevel)
     -E file               Log startup errors to file
     -v                    Show version number
     -V                    Show compile settings
     -h                    List available command line options (this page)
     -l                    List compiled in modules
     -L                    List available configuration directives
     -t -D DUMP_VHOSTS     Show parsed settings (currently only vhost settings)
     -S                    A synonym for -t -D DUMP_VHOSTS
     -t -D DUMP_MODULES    Show all loaded modules
     -M                    A synonym for -t -D DUMP_MODULES
     -t                    Run syntax check for config files
    

    Start/Stop/Reload ..

    # /etc/init.d/httpd [start|stop|restart|condrestart \
                        |reload|status|fullstatus|graceful|help|configtest]
    
    # service apache2 reload        (Using Sys V init scripts)
    

    A common startup problem

    $ httpd
    (98)Address already in use: make_sock: could not bind to address 127.0.0.1:80
    no listening sockets available, shutting down
    unable to open logs
    

    Non root users do not have permissions to start applications that bind to ports <= 1024.

    If more than one listen directive and they clash - /etc/httpd/httpd.conf

    listen *:80             (Listens on all system interfaces)
    listen 1.2.3.4:80       (Listens on a specific system interface)
    

    Can get the same error as above.

    Check that no other services are using same port

    # netstat -plant
    # lsof -i :80
    
  • Apache server deamon front end
    /usr/sbin/apachectl
    • A front end to the Apache server.
    • It is designed to help the administrator control the functioning of the Apache httpd daemon.
    • Uses SysV init-style options.
    apachectl <command | httpd arg>
    
    Command Description httpd eqivalent
    start Starts, gives error if already running httpd -k start
    stop Stops, active connections are aborted httpd -k stop, httpd -k restart
    graceful Restarts, active connections are NOT aborted httpd -k graceful
    graceful-stop Stops, active connections are NOT aborted httpd -d
    configtest Run a configuration file syntax test httpd -t
    status Report a status summary(needs 'link' package)
    fullstatus Displays a full status(needs 'link' package)
  • Apache2 server deamon front end
    /usr/sbin/apache2ctl
    • Apache2 control program.
    • it is a front-end for '/usr/sbin/apache2'
    • can be called with Sys. V init-style options
    • can be called with 'apache2' options
    Usage: /usr/sbin/apache2ctl start|stop|restart|graceful|graceful-stop|
                                configtest|status|fullstatus|help
           /usr/sbin/apache2ctl <apache2 args>
    
    apache2 options:
     -D name                         Define a name for use in <IfDefine name> directives   (httpd)
     -d directory                    Specify an alternate initial ServerRoot
     -f file                         Specify an alternate ServerConfigFile                 (httpd)
     -C "directive"                  Process directive before reading config files
     -c "directive"                  Process directive after reading config files
     -e level                        Show startup errors of level                          (httpd)
     -E file                         Log startup errors to file                            (httpd)
     -v                              Show version number
     -V                              Show compile settings                                 (httpd)
     -h                              List available command line options
     -k [start|restart|graceful
        |graceful-stop|stop]         SysV init-style options                               (httpd)
     -l                              List compiled in modules                              (httpd)
     -L                              List available configuration directives
     -t -D DUMP_VHOSTS               Show parsed settings, currently only vhost settings   (httpd)
     -S                              A synonym for -t -D DUMP_VHOSTS
     -t -D DUMP_MODULES              Show all loaded modules
     -M                              A synonym for -t -D DUMP_MODULES
     -t                              Run syntax check for config files                     (httpd)
     -X                              Debug mode, only one worker - do not detach
    

    Where flagged (httpd), the same 'apache2' options can be used with the 'httpd' command.

    Four ways to reload

    sudo apache2 -k reload           
    sudo httpd -k reload             (same options as 'apache2')
    
    sudo apache2ctl reload
    sudo service apache2 reload
    

    'sudo kill -HUP $( cat /var/run/apache2.pid; )' is another way ...'

    'apache2ctrl' behaviour

    Primarly controlled by variables set in /etc/apache2/envvars

    The default Debian configuration requires the environment variables APACHE_RUN_USER, APACHE_RUN_GROUP, and APACHE_PID_FILE to be set in /etc/apache2/envvars.

    $ more envvars
    # envvars - default environment variables for apache2ctl
    .....
    # Since there is no sane way to get the parsed apache2 config in scripts, some
    # settings are defined via environment variables and then used in apache2ctl,
    # /etc/init.d/apache2, /etc/logrotate.d/apache2, etc.
    export APACHE_RUN_USER=www-data
    export APACHE_RUN_GROUP=www-data
    export APACHE_PID_FILE=/var/run/apache2$SUFFIX.pid
    .....
    
  • Server access control
    Discretionary Access Control (DAC)

    Check validity of user credentials e.g. username/password

    Mandatory Access Controls (MAC)

    Validate aspects that the user cannot control, e.g. IP address of client

    Modules used to authenticate and authorise users are in the following table. In general the modules store valid credential information in one format or another. Their purpose is to protect resources.

    Module name Description
    mod_auth Provides user authentication via ordinary text files
    mod_access Provides restricted access to clients from a specific hostname or IP
    mod_auth_anon Allows anonymous user authentication for restricted areas
    mod_auth_db Provides access to restricted areas via user authentication via Berkley DB formatted files
    mod_auth_dbm Like mod_auth_db, save that credentials are stored in a DBM file
    mod_auth_digest Authentication method based on MD5, as opposed to Basic, stored in text file, manage with 'htdigest' tool

    Access control how-to

  • Authentication
    directives, .htaccess

    Two approaches:

    Use directives

    These inform security modules which authentication databases to use.

    Example directives - /etc/apache2/apache2.conf or /etc/httpd/httpd.conf

    AuthUserFile
    AuthDBMGroupFile
    <Directory /home/auser/public_html>              # Location of resource to protect
                                                     # - this includes sub-directories.
      <Files protect.me>                             # Resource being protected - file 'protect.me'
         AuthName "Any label"
         AuthType Basic                              # Type of authentication to use
         AuthUserFile /home/auser/protect.htpasswd   # Access credential file
         Require valid-user                          # Any user can access with valid credentials
      </Files>
    </Directory>
    

    Configure use of an access file - /etc/apache2/apache2.conf or /etc/httpd/httpd.conf

    AccessFileName .htaccess                         # Specify name of the access control file
    <Directory /dir/with/.htaccess/file>
       AllowOverride  All | none | directive-type    # Enable/disable use of .htaccess file
       .....
    <\Directory>
    

    Directives can be placed within virtual host sections, files.

    Use .htaccess files

    These can be placed in the directories to be protected. They restrict or grant user access to documents in or under a directory.

    File format - .htaccess

    # Contains two sections:
    
    # 1st. Section
    # Contains the names of the password or group file to use
    AuthUserFile {path to passwd file}
    AuthGroupFile {path to group file}
    AuthName {title for dialog box}
    AuthType Basic
    
    # 2nd. Section
    # Contains access rights to ensure that only user {username} 
    # can access the current directory
    <Limit GET>
     require user {username}
    </Limit&gt
    

    The 'Limit' section can contain other directives e.g. allow access based on IPs, allow users who are part of a set of users/group.

    Example - .htaccess

    <Files foo.php>
     Order Deny,Allow
     Deny from All
     Allow from 10.0.0.0/255.0.0.0
     AuthName "Insiders Only"
     AuthType Basic
     AuthUserFile /usr/local/web/apache/.htpasswd-foo
     Require valid-user
     Satisfy Any
    </Files>
    

    Permit any client on the local network(10.*.*.*) to access the 'foo.php' page without hindrance but require a username and password for anyone else.

    Autorisation and authentication how-to

  • Create and update password files
    htpasswd
    • mod_auth uses plain text user files "username:password", password field should be encrypted.
    • 'htpasswd' creates and updates the flat-files used to store "username:password" - for basic authentication of HTTP users.
    htpasswd [-cmdpsD]  passwordfile username
             -b[cmdpsD] passwordfile username password
             -n[mdps]   username
    
    Options:
     -c                 Create a new file.
     -n                 Don't update file; display results on stdout.
     -m                 Force MD5 encryption of the password.
     -d                 Force CRYPT encryption of the password (default).
     -p                 Do not encrypt the password (plaintext).
     -s                 Force SHA encryption of the password.
     -b                 Use the password from the command line rather 
                        than prompting for it.
     -D                 Delete the specified user.
    

    Create a new password file, add user fred to it

    # htpasswd -c /etc/httpd/user-pass.list fred         (Prompts for fred's password)
    
  • User authentication via a DBM files
    dbmmanage
    • to use a DBM database (as used by mod_auth_db) use 'dbmmanage'.
    • the user authentication file is configured via the AuthUserFile directives in either the httpd.conf or in the .htaccess file.
    • 'dbmmanage' creates and updates the DBM format files used to store usernames and password for basic authentication of HTTP users via mod_authn_dbm.
    dbmmanage [encoding] filename command username 
              [encpasswd [group[,group...] [comment]]]
    dbmmanage filename view [username]
    dbmmanage filename import
    
    Encodings:
     -d           crypt encryption (default, except on Win32, Netware)
     -m           MD5 encryption (default on Win32, Netware)
     -s           SHA1 encryption
     -p           plaintext (not recommended)
    

    Options

     filename     The filename of the DBM format file. Usually without the 
                  extension .db, .pag or .dir.
     username     The user for which the operations are performed. The 
                  username may not contain a colon (:).
     encpasswd    Use an already encrypted password. (update and add commands).
                  hyphen (-) will prompt for the password, fill in the fields
                  afterwards. 
                  period (.) keeps the original password untouched (update command).
     group        A group, which the user is member of. A groupname may not contain
                  a colon (:).
                  hyphen (-) if you don't want to assign the user to a group, but 
                  fill in the comment field.
                  period (.) keeps the original groups untouched (update command).
     comment      Comments - the  server will ignore this field.
    

    Commands

     add          Adds an entry for username to filename using the encrypted
                  password encpasswd. e.g.
                  # dbmmanage passwords.dat add rbowen foKntnEF3KSXA
     adduser      Asks for a password and then adds an entry for username to
                  filename. e.g.
                  # dbmmanage passwords.dat adduser krietz
     check        Asks for a password and then checks if username is in filename
                  and if it's password matches the specified one. e.g.
                  # dbmmanage passwords.dat check rbowen
     delete       Deletes the username entry from filename. 
                  e.g. # dbmmanage passwords.dat delete rbowen
     import       Reads username:password entries (one per line) from STDIN and
                  adds to filename. The passwords already have to be encrypted.
     update       Same as the adduser command, except that it makes sure username
                  already exists in filename. e.g.
                  # dbmmanage passwords.dat update rbowen
     view         Just displays the contents of the DBM file. If you specify
                  a username, it displays the particular record only. e.g.
                  # dbmmanage passwords.dat view
    
  • Group authentication
    AuthGroupFile
    • deny or allow access based on group membership.
    • the group file contains a list of groups and members, the members (usernames) should be in the password file.

    Authentication file format

    group1: username1 username2 ...
    group2: username1 username3 ...
    
    • read permissions for the group file need to have been set for everyone.
    • the group file is configured via the AuthGroupFile directives in either the httpd.conf or into the .htaccess file.
    • make sure that the AuthGroupFile is stored outside the document tree of the web-server; do not put it in the directory that it protects. Otherwise, clients may be able to download the AuthGroupFile.

    AuthGroupFile usage example

    AuthGroupFile /etc/httpd/groups/groupfile
    <Limit GET>
         require group mygroup           # Only members of mygroup listed in 
                                         # /etc/httpd/groups/groupfile can access
    </Limit>
    

    In 'httpd.conf' or 'apache2.conf' or '.htaccess' or virtual host files.

  • Satisfy directive
    usage example

    Used to specify that several criteria may be considered when trying to decide if a user will be granted access. Takes one argument - 'all' or 'any'.

    Satisfy all

    Access if all specified criteria are satisfied/met (default)

    Satisfy any

    Access if any of the specified criteria are/is satisfied/met

    <Directory /usr/local/apache/htdocs/protected-secret>
         AuthType Basic
         AuthName intranet
         AuthUserFile /www/passwd/users
         AuthGroupFile /www/passwd/groups
         Require group customers
         Order allow,deny
         Allow from internal.com
         Satisfy any
    </Directory>
    

    In 'httpd.conf' or 'apache2.conf' or '.htaccess' or virtual host files.

    • Directory /usr/local/apache/htdocs/protected-secret is password protected for external network access.
    • All hosts on the internal network will be given free access to the resource (no password required).
  • Allow, Deny directive
    usage example

    Allow and deny access based on the host name or host IP of the machine requesting a document.

    Goes hand-in-hand with the Order directive which gives precedence between the accept list and the deny list.

    .....
    Allow from 123.4.5.6
    Deny from host.domain.com another.host.com
    Order Deny,Allow
    Deny from all
    Allow from hostname.example.com
    

    In 'httpd.conf' or 'apache2.conf' or '.htaccess' or virtual host files.

  • Virtual hosts
    Name-based
    • the server relies on the client (e.g. the browser) to report the hostname as part of the HTTP headers
    • many different hosts can share the same IP address
    • if no match then the first defined virtual host container becomes the default - overriding the main section of the config file unless there is a catchall at the end

    Configuration steps

    • Configure DNS server to map each hostname to the correct IP address.
    • Configure Apache HTTP Server to recognise the different hostnames.
    • Designate the IP address (and possibly port) on the server that will be accepting requests for the hosts.

    Create a block for each different host to serve

    NameVirtualHost *                       # Expect name-based virtual hosts
                                            # IP address on which the server will receive requests for the
                                            # name-based virtual hosts, * => any IP
    <VirtualHost "bar.example.org">
        DocumentRoot /var/www/bar           # Bare minimum directives; create an index.php file here
        ServerName bar.example.org          # Bare minimum directives
        ServerAlias example.org             # This virtual host will also respond to this request
    </VirtualHost>
    <VirtualHost *>                         # A catchall virtual host, if a virtual host cannot be found matching
                                            # the IP address/web domain of the client then this one is served
        DocumentRoot /var/www
    </VirtualHost>
    

    In 'httpd.conf' or 'apache2.conf'.

    When a request arrives

    the server will first check if it is using an IP address that matches the NameVirtualHost

    if it is, then it will look at each section with a matching IP address and try to find one where the ServerName or ServerAlias matches the requested hostname.

    if it finds one, then it uses the configuration for that server.

    if no matching virtual host is found, then the first listed virtual host that matches the IP address will be used.

    Configuration directives set in the main server context (outside any container) will be used only if they are not overridden by the virtual host settings.

    NB. NameVirtualHost 12.34.0.1:8790 does not automatically make the server listen on this IP address, use the BindAddress and Listen directives as well.

  • Debian, Mint name-based virtual host

    Same info used as above but in a more modular approach as opposed to all entries in one posibly quite large httpd.conf, apache2.conf file.

    /etc/apache2/ports.conf

    .....
    NameVirtualHost *:80
    #NameVirtualHost 127.0.0.1:80
    ServerName mark-desktop
    Listen 80
    
    <IfModule mod_ssl.c>
        .....
        Listen 443
    </IfModule>
    
    <IfModule mod_gnutls.c>
        Listen 443
    </IfModule>
    

    /etc/apache2/sites-available

    blog  c5  default  default-ssl  gallery  linref  nixref  skeleton  wp
    

    Each file contains the directives that represent a virtual host.

    nixref virtual host - /etc/apache2/sites-available/nixref

    <VirtualHost *:80>
            ServerName nixref
        DocumentRoot /home/markw049/www/nixref
    
        <Directory />
            Options FollowSymLinks
            AllowOverride None
        </Directory>
    
        <Directory /home/markw049/www/nixref/>
            Options FollowSymLinks MultiViews
            # AllowOverride None
                    # so .htaccess rules can rewrite a url
            AllowOverride All
            Order allow,deny
            allow from all
        </Directory>
    </VirtualHost>
    

    Worth noting that the format of the <VirtualHost *:80> section header needs to match that used in '/etc/apache2/ports.conf' or that used in 'httpd.conf' 'aoache2.conf.

    Enable name resolution - at home so /etc/hosts

    127.0.0.1   localhost c5 gallery blog skeleton linref nixref
    127.0.1.1   mark-desktop
    .....
    

    Enable, disable a virtual host - a2ensite, a2dissite (debian)

    $ sudo a2ensite c5 linref
    Enabling site c5.
    Enabling site linref.
    To activate the new configuration, you need to run:
      service apache2 reload
    
    $ sudo a2dissite c5 linref
    Site c5 disabled.
    Site linref disabled.
    To activate the new configuration, you need to run:
      service apache2 reload
    

    An enabled site has a symbolic link created in '/etc/apache2/sites-enabled' which points to the site's virtual host file in '/etc/apache2/sites-available'.

  • No browser support for name-based virtual hosts
    (dated)

    I'm guessing it is dated - hard to think of any browser (these days) that would not support name-based virtual hosting.

    Some client browsers do not support the name-based virtual hosts. A workaround is required. Without the workaround a client would get the server's real main page.

    The work around involves redirecting traffic to the right place using a ServerPath directive which should be placed in the VirtualHost section.

    Name-based virtual host workaround

    <VirtualHost www.company.com>
        ServerName www.company.com
        DocumentRoot /usr/local/htdocs/company
        ServerPath /company
    </VirtualHost>
    

    In 'httpd.conf' or 'apache2.conf' or '.htaccess' or virtual host files.

    The ServerPath directive will redirect all requests beginning with the /company to /usr/local/htdocs/company. The HTML documents should contain only relative links, making them accessible from any browser.

  • Virtual hosts
    IP-based
    • each (web)domain has it's own unique IP address
    • the IP of the connection determines the correct virtual host to serve
    • a physical host can have more than one IP address => can serve more than one (web)domain
    • if no virtual host match the main section is used.

    Reasons for using:

    • Name-based cannot be used with SSL secure servers.
    • Some ancient clients are not compatible with name-based virtual hosting.
    • Require hosts to have separate IPs.

    The web server must have a different IP address for each IP-based virtual host. This can be achieved either via multiple NICs or use of virtual interfaces (IP aliasing).

    Two ways of configuring Apache to support multiple hosts:

    (a) Running a separate httpd daemon for each hostname - multiple daemons

    • wish to maintain strict separation between the web-pages for separate customers
    • need one daemon per customer, each running with different User, Group, Listen and ServerRoot settings
    • can afford the memory and file descriptor requirements of listening to every IP alias on the machine
    • create a separate httpd installation for each virtual host
    • for each installation, use the Listen IP directive in the configuration file to select which IP address (or virtual host) that daemon services.
    BindAddress 192.168.2.2              # Restricts server to listen on a single address (deprecated)
    BindAddress *                        # Listens on all configured interfaces (deprecated)
    
    # Permit multiple Apache servers on
    # the same machine to listen to 
    # different IP addresses
    Listen 64.41.64.172:8080             # Restricts a single server to listen on this address[:port]
    Listen 192.168.2.2:8000              # Another server listens on this address[:port]
    

    In 'httpd.conf', 'apache2.conf'. On debian can use '/etc/apache2/ports.conf'.

    (b) Running a single daemon which supports all the virtual hosts

    • sharing of the httpd configuration between virtual hosts is acceptable
    • the machine serves a large number of requests and so the performance loss in running separate daemons may be significant.
    • a single httpd will service requests for the main server and all the virtual host
    • VirtualHost directive in the configuration file is used to set the values of ServerAdmin, ServerName, DocumentRoot, ErrorLog and TransferLog or CustomLog configuration directives to different values for each virtual host.
    <VirtualHost www.smallco.com>
        ServerAdmin webmaster@mail.smallco.com
        DocumentRoot /groups/smallco/www
        ServerName www.smallco.com
        ErrorLog /groups/smallco/logs/error_log
        TransferLog /groups/smallco/logs/access_log
    </VirtualHost>
    <VirtualHost www.baygroup.org>
        ServerAdmin webmaster@mail.baygroup.org
        DocumentRoot /groups/baygroup/www
        ServerName www.baygroup.org
        ErrorLog /groups/baygroup/logs/error_log
        TransferLog /groups/baygroup/logs/access_log
    </VirtualHost>