How to install Apache on Ubuntu 20.04?

The Apache HTTP Server Project is a community effort to develop and maintain a “free software” HTTP server for modern operating systems (UNIX, GNU / Linux, BSD, Windows).

In this post we’re going to configure Apache as a reverse proxy in front of PHP-FPM service.

A reverse proxy is a type of proxy server that processes http (s) requests and distributes them transparently to one or more backend servers.

I recommend to read Install and configure Apache HTTP server before continue

Install the server

$ sudo apt install apache2

Admin the apache2 service

In this part we will learn how to start, stop or restart the apache2 service, using the systemctl command, systemctl is part of the systemd suite (systemd is a replacement for the SysV initialization system and also a set of configuration and management services for the GNU/Linux operating system)

Check the status

With the following command we check if the web server is running successfully, note the line Active: active (running)

$ sudo systemctl status apache2
● apache2.service - The Apache HTTP Server
     Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
     Active: active (running) since Sat 2020-10-31 15:02:47 UTC; 1h 25min ago
       Docs: https://httpd.apache.org/docs/2.4/
    Process: 620 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS)
    Process: 1611 ExecReload=/usr/sbin/apachectl graceful (code=exited, status=0/SUCCESS)
   Main PID: 666 (apache2)
      Tasks: 55 (limit: 1075)
     Memory: 9.7M
     CGroup: /system.slice/apache2.service
             ├─ 666 /usr/sbin/apache2 -k start
             ├─1615 /usr/sbin/apache2 -k start
             └─1643 /usr/sbin/apache2 -k start
...

Start the service

If the service is stoped (Active: inactive) you can sart it with:

$ sudo systemctl start apache2

Restart the service

To apply any modification that you did to the configuration file, you must restart the server with the following command:

$ sudo systemctl restart apache2

Refresh configuration

It’s better to refresh configuration using the following command because in this way the server will reload the changes without losing connections.

$ sudo systemctl reload apache2

Stop the service

If you want to stop the service run the following command:

$ sudo systemctl stop apache2

Start the service with the operating system

You can find out if the apache2 service will start automatically after an operating system reboot by running the following command:

$ sudo systemctl is-enabled apache2
enabled

The output of the above command is enabled or disabled, if it is disable execute:

$ sudo systemctl enable apache2
Synchronizing state of apache2.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install enable apache2

If you want it not to start with the operating system run:

$ sudo systemctl disable apache2
Synchronizing state of apache2.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install disable apache2
Removed /etc/systemd/system/multi-user.target.wants/apache2.service.

Verify loaded modules

You can extend the Apache functionalities by selecting a set of modules: the modules are compiled as Dynamic Shared Objects (DSO) and can be activated and deactivated using the LoadModule directive.

With the following command we verify what modules are the actives.

$  apachectl -M
Loaded Modules:
 core_module (static)
 so_module (static)
 watchdog_module (static)
 http_module (static)
 log_config_module (static)
 logio_module (static)
 version_module (static)
 unixd_module (static)
 access_compat_module (shared)
 alias_module (shared)
 auth_basic_module (shared)
 authn_core_module (shared)
 authn_file_module (shared)
 authz_core_module (shared)
 authz_host_module (shared)
 authz_user_module (shared)
 autoindex_module (shared)
 deflate_module (shared)
 dir_module (shared)
 env_module (shared)
 filter_module (shared)
 mime_module (shared)
 mpm_event_module (shared)
 negotiation_module (shared)
 reqtimeout_module (shared)
 setenvif_module (shared)
 status_module (shared)

Enable mod_rewrite

mod_rewrite is a powerful and sophisticated Apache web server module that allows URL rewriting using regular expressions (PCRE).

$ sudo ln -s /etc/apache2/mods-available/rewrite.load /etc/apache2/mods-enabled/rewrite.load
$ sudo systemctl restart apache2

See:

Enable mod_proxy

mod_proxy is the main proxy module that allows to redirect http (s) requests to the underlying application servers.

$ sudo ln -s /etc/apache2/mods-available/proxy.load /etc/apache2/mods-enabled/proxy.load
$ sudo systemctl restart apache2

Enable mod_proxy_fcgi

mod_proxy_fcgi is a module that allows to communicate with the FastCGI server. This module requires the mod_proxy module.

$ sudo ln -s /etc/apache2/mods-available/proxy_fcgi.load /etc/apache2/mods-enabled/proxy_fcgi.load
$ sudo systemctl reload apache2

VirtualHost configuration

Virtual hosting allows to host several domains on the same server, sharing server resources, so you can have serveral VirtualHost in the same server.

Some directives:

  • VirtualHost: Encapsulates several directives in the same block defining the characteristics of the VirtualHost, the most common use is a website, the *: 80 value means that this virtual host is available on port 80 and on all IP addresses allowed by the Listen directive, if you want to establish a secure connection you must configure a SSL certificate and use the 443 port by default.

  • ServerName: Main URL for your web site.

  • ServerAdmin: Contact address that is included in any error page. If httpd does not recognize the supplied argument as a URL, it assumes it is an email address and prefixes it with mailto. If you want to use a URL, it must point to another server under your control. Otherwise, users may not be able to contact you in case of errors.

  • ErrorLog: File name where the server dump errors. If the file path is not absolute, it is assumed to be relative to ServerRoot. Note the use of the environment variable APACHE_LOG_DIR which is defined in the file /etc/apache2/envars

  • CustomLog: File name where the server dump request log.

  • Directory: It is used to encapsulate a group of directives that will be applied to the specified directory and subdirectories, in this case the directive AllowOverride is applied to the directory /var/www/wordpress and to the directories that are found under the wordpress directory.

  • AllowOverride: Together with the directive AllowOverrideList determines if .htaccess file is allowed and which directives can be overridden by the .htaccess, a value of All means that all directives can be overridden, a value of None means that the directives specified in AllowOverrideList can be overridden if both directives have the value of None then .htaccess is not allowed.

  • FilesMatch: Applies the directives enclosed in the block to all files that match the pattern or regular expression, for example appliest the SetHandler directive to all PHP files.

  • SetHandler: Apply a specific handler to all matching files. A “handler” is an internal Apache representation of the action that to be performed over the matching files, in our case all PHP files will be processed FHP-FPM service, the Apache server will try to communicate with the PHP-FPM service via unix socket or via TCP/IP socket, if you have Apache and PHP-FPM service on different servers the communication should be done using TPC/IP socket.

Check Install and configure Apache HTTP server for more information about other directives and general configuration.

Create the configuration file

It is recommended to create a configuration file for each virtual site under the directory /etc/apache2/sites-available/:

$ sudo touch /etc/apache2/sites-available/mysite.conf

Add the following configuration.

<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    ServerName www.midominio.com

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/wordpress
    DirectoryIndex index.php
    # 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

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    <Directory /var/www/wordpress>
        AllowOverride All
    </Directory>
    <FilesMatch \.php$>
        # Unix sockets require 2.4.7 or later    
        # SetHandler "proxy:unix:/run/php/php7.4-fpm.sock"
        # TCP/IP socket
        SetHandler "proxy:fcgi://192.168.100.82:9000"
    </FilesMatch>
</VirtualHost>

The directory /var/www/wordpress must exist and be accessible to both Apache and the PHP-FPM service.

If the previous configuration does not work for you, check the files error.log and access.log , on these files Apache dump errors and web requests respectively.

Activate the site

$  sudo ln -s /etc/apache2/sites-available/mysite.conf /etc/apache2/sites-enabled/mysite.conf 

Refresh configuration:

 sudo systemctl reload apache2

Further readings


YouTube video

Install LAMP Stack in Ubuntu 20.04, 2 (2)

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.