Skip to main content

Apache Web Server

Common Checks

  • Checking the status of web server
    • sudo systemctl status apache2
  • Stopping the web server
    • sudo systemctl stop apache2
  • Starting the web server
    • sudo systemctl start apache2
  • Restart the web server
    • sudo systemctl restart apache2
  • Enable the web server service (service start up at boot)
    • sudo systemctl enable apache2
  • Disable the web server service (server will NOT start up at boot)
    • sudo systemctl disable apache2

Configurations

  • /etc/apache2 : apache config directory, all of apache config files resides here
  • /etc/apache2/apache2.conf

Virtual Hosts

Virtual hosts allows hosting more than one domain from a single server

  1. Create directory for your_domain sudo mkdir /var/www/your_domain

  2. Assign ownership of directory to another user (optional) sudo chown -R <user>:<user> /var/www/your_domain

  3. Allow owner to read, write and execute files (while granting only read and execute to groups and others) sudo chmod -R 755 /var/www/your_domain

  4. Create sample index.html using nano sudo nano /var/www/your_domain/index.html Add the following:

    <html>
        <head>
            <title>This is a test page</title>
        </head>
        <body>
            <h1>Success! The your_domain virtual host is working!</h1>
        </body>
    </html>
    
  5. Add a new configuration for the site at /etc/apache2/sites-available/your_domain.conf sudo nano /etc/apache2/sites-available/your_domain.conf Add the following:

    <VirtualHost *:80>
        ServerAdmin webmaster@localhost
        ServerName your_domain
        ServerAlias www.your_domain
        DocumentRoot /var/www/your_domain
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
    
    • ServerAdmin should point to an email that the site admin can access
    • DocumentRoot points to the directory
    • ServerName establishes the base domain that will match the virtual host definition
    • ServerAlias defines further names that will match as if they were the base name

    Alternatively add an ssl site too sudo nano /etc/apache2/sites-available/your_domain-ssl.conf

    <IfModule mod_ssl.c>
    <VirtualHost *:443>
        ServerAdmin webmaster@localhost
        ServerName awharf.xyz
        ServerAlias www.awharf.xyz
        DocumentRoot /home/awharf/www/awharf.xyz
    
        # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
        # error, crit, alert, emerg.
        # It is also possible to configure the loglevel for particular
        # modules, e.g.
        #LogLevel info ssl:warn
    
        # For most configuration files from conf-available/, which are
        # enabled or disabled at a global level, it is possible to
        # include a line for only one particular virtual host. For example the
        # following line enables the CGI configuration for this host only
        # after it has been globally disabled with "a2disconf".
        #Include conf-available/serve-cgi-bin.conf
    
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
    
        SSLCertificateFile /etc/letsencrypt/live/awharf.xyz/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/awharf.xyz/privkey.pem
        Include /etc/letsencrypt/options-ssl-apache.conf
    </VirtualHost>
    </IfModule>
    
  6. Enable the file with a2ensite tool cd /etc/apache2/sites-available sudo a2ensite your_domain.conf sudo a2ensite your_domain-ssl.conf NOTE: a2ensite must be run in the sites-available directory!

  7. Disable the default site defined in 000-default.conf sudo a2dissite 000-default.conf <- disable port 80 default (http) sudo a2dissite 000-default-le-ssl.conf <- disable port 443 default (https)

  8. Test for configuration errors sudo apache2ctl configtest

  9. Restart apache to implement changes sudo systemctl reload apache2 sudo systemctl restart apache2

Hosting from a different DocumentRoot (other than /var/www)

  1. nano /etc/apache2/apache2.conf
  2. Add the following: (replace /home/awharf/www to whatever directory you are using)
    ########################################################################
    <Directory /home/awharf/www/>
            Options Indexes FollowSymLinks
            AllowOverride None
            Require all granted
    </Directory>
    ########################################################################
    
  3. If the server returns .htaccess error, go to read your apache error log at /var/log/apache2/error.log
  4. Do the following on the directories that aren't granting access sudo chmod 755 <site_top_folder>
  5. Reload and restart accordingly sudo systemctl reload apache2 sudo systemctl restart apache2

.htaccess

Required for and rewriting / redirecting:

# Enable the rewrite engine
RewriteEngine On
  • Error 404 redirect

    # 404 direct to 404.html
    ErrorDocument 404 /404.html
    RewriteCond %{HTTPS} !=on
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
    

    Add to virtual host

    <VirtualHost>
        ...
        ErrorDocument 404 /error404.html
        ...
    </VirtualHost>
    
  • Short URL https://www.mediawiki.org/wiki/Manual:Short_URL/Apache

    # Short URL for wiki pages
    RewriteRule ^/?w(/.*)?$ %{DOCUMENT_ROOT}/wiki/index.php [L]
    
    # Redirect / to Main Page
    RewriteRule ^/w*$ %{DOCUMENT_ROOT}/wiki/index.php [L]
    

Locking a directory

Taken from https://www.digitalocean.com/community/tutorials/how-to-set-up-password-authentication-with-apache-on-ubuntu-14-04

  1. Create the password file (if not created) (skip to next if created) sudo htpasswd -c /etc/apache2/.htpasswd <username>
  2. Add additional users to the password file sudo htpasswd /etc/apache2/.htpasswd <another_user>
  3. Look at the contents to ensure everything configured correctly cat /etc/apache2/.htpasswd
  4. Enable it into the site sudo nano /etc/apache2/sites-enabled/domain_name.conf Add the following: (e.g. locking /var/www/html here)
    <Directory "/var/www/html">
        AuthType Basic
        AuthName "Restricted Content"
        AuthUserFile /etc/apache2/.htpasswd
        Require valid-user
    </Directory>
    
  5. Reload and restart

Installation

From: https://www.digitalocean.com/community/tutorials/how-to-install-the-apache-web-server-on-ubuntu-22-04

  1. Install Apache

    • sudo apt update (apache is in ubuntu default software repositories)
    • sudo apt install apache2
  2. Adjusting firewall for access to web portals

    • sudo ufw allow 'Apache'
    • sudo ufw allow 443 (for SSL/TLS enabled apache)
    • sudo ufw status -- verify
    • Error Encounters:
      AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
      
      • edit /etc/apache2/apache2.conf
      • insert ServerName localhost
      • restart sudo systemctl reload apache2
  3. Checking Web Server Status

    • sudo systemctl status apache2

    • hostname -I - retrieve up address (first one)

    • curl -4 icanhazip.com ^ another method to get address

    • Error Encounters:

      ERR_CONNECTION_TIMED_OUT
      
      1. Allow port 443
      This site can’t provide a secure connection
      X.X.X.X sent an invalid response.
      ERR_SSL_PROTOCOL_ERROR
      
      1. enable SSL on apache sudo a2enmod ssl

      2. install openssl sudo apt-get install openssl

      3. ensure port 443 is open

      4. change /etc/aphache2/ports.conf to this

        # NameVirtualHost *:80
        Listen 80
        
        <IfModule mod_ssl.c>
            # If you add NameVirtualHost *:443 here, you will also have to change
            # the VirtualHost statement in /etc/apache2/sites-available/default-ssl
            # to <VirtualHost *:443>
            # Server Name Indication for SSL named virtual hosts is currently not
            # supported by MSIE on Windows XP.
            # NameVirtualHost *:443
            Listen 443
        </IfModule>
        
        <IfModule mod_gnutls.c>
                Listen 443
        </IfModule>
        
      5. NOTE: For this step onwards, chrome does not support a self-assigned SSL key, you need firefox to see your website working! and make use to use http, without the s.

      6. generate a self-assigned SSL key for testing purposes source: https://httpd.apache.org/docs/2.0/ssl/ssl_faq.html#selfcert

        1. Go to apache folder and create a folder called ssl
        2. Go to /etc/apache/ssl
        3. Run openssl req -new -x509 -nodes -out server.crt -keyout server.key (create server.key and server.crt files, server can be any name!)
        4. edit /etc/apache2/httpd.conf (default is empty) replace MYSITE.COM with your name used above (above example uses server)
          <VirtualHost _default_:443> 
          ServerName MYSITE.COM:443
          SSLEngine on
          SSLCertificateKeyFile /etc/apache2/ssl/MYSITE.COM.key
          SSLCertificateFile /etc/apache2/ssl/MYSITE.COM.crt
          ServerAdmin MYWEBGUY@localhost
          DocumentRoot /var/www
          <Directory />
              Options FollowSymLinks
              AllowOverride None
          </Directory>
          <Directory /var/www/>
              Options Indexes FollowSymLinks MultiViews
              AllowOverride None
              Order allow,deny
              allow from all
          </Directory>
          
          
          ErrorLog ${APACHE_LOG_DIR}/errorSSL.log
          
          # Possible values include: debug, info, notice, warn, error, crit,
          # alert, emerg.
          LogLevel warn
          
          CustomLog ${APACHE_LOG_DIR}/accessSSL.log combined
          
          </VirtualHost>
          
        5. You should now see your site if you use the http://X.X.X.X link!
        6. More info: https://httpd.apache.org/docs/2.0/ssl/ssl_faq.html#selfcert
        7. Remove to remove these after not in use!!!!!
    • After the SSL errors to allow modern browsers to view the site is fixed, proceed on with the SSL Certificate