One place for hosting & domains

      Apache

      Как установить веб-сервер Apache в Ubuntu 18.04


      Введение

      HTTP сервер Apache является самым широко используемым веб-сервером в мире. Он предоставляет множество удобных функций включая динамически загружаемые модули, широкую поддержку мультимедиа, и интеграцию с другим популярным программным обеспечением.

      В этом руководстве мы расскажем, как установить веб-сервер Apache на ваш сервер с Ubuntu 18.04.

      Необходимые условия

      Перед тем, как начать следовать шагам, описанным в этом руководстве, вам необходимо настроить отдельный, не-рутовый (non-root) профиль пользователя на вашем сервере с Ubuntu 18.04. Кроме того, вам потребуется настроить базовый файрвол для блокирования всех портов, кроме необходимых для работы Apache. Вы можете ознакомиться с процессом настройки аккаунта пользователя и настройкой файрвола на вашем сервере следуя шагам нашего руководства по первичной настройке сервера на Ubuntu 18.04.

      После завершения создания аккаунта войдите на ваш сервер с помощью вновь созданного пользователя.

      Шаг 1 – Установка Apache

      Apache доступен из дефолтных репозиториев Ubuntu, что позволяет устанавливать его с помощью средств управления пакетами.

      Давайте начнём с обновления локального индекса пакетов:

      Далее установим пакет apache2:

      После подтверждения установки apt установит Apache и все необходимые зависимости.

      Шаг 2 - Настройка файрвола

      Перед тестированием установки Apache необходимо изменить настройки файрвола для разрешения доступа извне к дефолным веб-портам. Если вы следовали инструкциям по настройке файрвола из руководства по первичной настройке сервера, ваш файрвол UFW уже должен быть настроен таким образом, чтобы ограничивать доступ к вашему серверу.

      В процессе установки Apache регистрирует себя в конфигурации UFW, создавая несколько профилей приложения, которые могут быть использованы для включения и отключения доступа к Apache через файрвол.

      Выведем профили приложений ufw следующей командой:

      Вы увидите список приложений пользователей:

      Вывод

      Available applications: Apache Apache Full Apache Secure OpenSSH

      Как видно из этого вывода, для Apache доступно три профиля:

      • Apache: этот профиль открывает порт 80 (обычный, не шифрованный веб-трафик).
      • Apache Full: этот профиль открывает порты 80 (обычный, не шифрованный веб-трафик) и 443 (трафик шифруется с помощью TLS/SSL).
      • Apache Secure: этот профиль открывает только порт 443 (трафик шифруется с помощью TLS/SSL).

      Рекомендуется включать самый ограниченный профиль, который будет позволять входящий трафик. Поскольку мы не настраивали SSL для нашего сервера в этом руководстве, нам потребуется включить только порт 80:

      Вы можете проверить внесённые изменения командой:

      В выводе вы должны видеть, что HTTP трафик разрешён:

      Вывод

      Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere Apache ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) Apache (v6) ALLOW Anywhere (v6)

      Как видно из этого вывода профиль был включен для разрешения доступа к веб-серверу.

      Шаг 3 - Проверка вашего веб-сервера

      После завершения процесса установки Ubuntu 18.04 запустит Apache. Веб-сервер уже должен быть запущен.

      Проверим в системе инициализации systemd, что сервис работает, следующей командой:

      • sudo systemctl status apache2

      Вывод

      ● apache2.service - The Apache HTTP Server Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled) Drop-In: /lib/systemd/system/apache2.service.d └─apache2-systemd.conf Active: active (running) since Tue 2018-04-24 20:14:39 UTC; 9min ago Main PID: 2583 (apache2) Tasks: 55 (limit: 1153) CGroup: /system.slice/apache2.service ├─2583 /usr/sbin/apache2 -k start ├─2585 /usr/sbin/apache2 -k start └─2586 /usr/sbin/apache2 -k start

      Как видно из представленного вывода, сервис выглядит работающим корректно. Тем не менее, самый надёжный способ проверить работу Apache - это запросить веб-страницу.

      Вы можете запросить дефолтную веб-страницу Apache с помощью IP адреса вашего сервера. Если вы не знаете IP адрес вашего сервера, вы можете найти его несколькими способами с помощью командной строки.

      Введите следующую команду:

      Она вернёт несколько адресов, разделённых пробелами. Вы можете попробовать каждый из них в вашем веб-браузере.

      Другой способ заключается в использовании команды, которая позволяет увидеть ваш IP адрес из другого места в сети Интернет:

      После того, как вы найдёте IP адрес вашего сервера, введите его в свой веб-браузер:

      • http://IP_адрес_вашего_сервера

      Вы должны увидеть дефолтную страницу Apache для Ubuntu 18.04:

      Дефолтная страница Apache

      Эта страница свидетельствует о том, что Apache работает корректно. На этой странице также представлена базовая информация о важных файлах и директориях Apache.

      Шаг 4 - Управление процессом Apache

      Теперь, когда у вас есть работающий веб-сервер, рассмотрим некоторые базовые команды для управления им.

      Для остановки себ-сервера наберите:

      • sudo systemctl stop apache2

      Для запуска остановленного сервера наберите:

      • sudo systemctl start apache2

      Для перезапуска сервиса наберите:

      • sudo systemctl restart apache2

      Если вы вносите какие-то изменения в конфигурацию, Apache зачастую может перезагружаться без потери открытых соединений. Для этого наберите команду:

      • sudo systemctl reload apache2

      По умолчанию Apache сконфигурирован на запуск при загрузке сервера. Вы можете отключить такое поведение следующей командой:

      • sudo systemctl disable apache2

      Для повторного включения сервиса при загрузке сервера наберите:

      • sudo systemctl enable apache2

      Теперь Apache должен опять запускаться автоматически при загрузке сервера.

      Шаг 5 - Настройка виртуальных хостов (рекомендуется)

      При использовании веб-сервера Apache вы можете использовать виртуальные хосты (аналог серверных блоков в Nginx) для хранения конфигурационных настроек разных сайтов. Это позволяет иметь более одного сайта на одном сервере. В этом руководстве мы будем для примера использовать доменное имя example.com, но вам следует заменить его вашим собственным доменным именем. Для того, чтобы узнать больше о настройке доменных имён в DigitalOcean, рекомендуем ознакомиться с нашим Введением в DNS DigitalOcean.

      Apache для Ubuntu 18.04 уже имеет один виртуальный хост, включенный по умолчанию, который настроен на отдачу документов из директории /var/www/html. Хотя это и удобно для обслуживания одного сайта, это становится неудобным, когда сайтов несколько. Вместо того, чтобы изменять /var/www/html, давайте создадим новую структуру директорий внутри /var/www для нашего сайта example.com, оставив /var/www/html для показа дефолтной страницы пользователям в случаях, когда клиентский запрос не совпадает ни с одним из настроенных доменных имён.

      Создайте директорию для example.com используя флаг -p для создания необходимых родительских директорий:

      • sudo mkdir -p /var/www/example.com/html

      Далее настройте владельца директории с помощью переменной окружения $USER:

      • sudo chown -R $USER:$USER /var/www/example.com/html

      Теперь права должны для корневой директории быть настроены правильным образом при условии, что вы не меняли своё значение umask. На всякий случай мы можем удостовериться в этом командой:

      • sudo chmod -R 755 /var/www/example.com

      Далее создадим страницу index.html в nano или любом другом текстовом редакторе:

      • nano /var/www/example.com/html/index.html

      Добавим в файл следующий HTML:

      /var/www/example.com/html/index.html

      <html>
          <head>
              <title>Welcome to Example.com!</title>
          </head>
          <body>
              <h1>Success!  The example.com server block is working!</h1>
          </body>
      </html>
      

      Сохраните и закройте файл.

      Для того, чтобы Apache мог отдавать этот контент, нам необходимо настроить виртуальный хост с корректными настройками. Вместо того, чтобы редактировать существующий файл виртуального хоста /etc/apache2/sites-available/000-default.conf, создадим новый файл для нашего сайта - /etc/apache2/sites-available/example.com.conf:

      • sudo nano /etc/apache2/sites-available/example.com.conf

      Скопируйте следующий текст настроек виртуального хоста в созданный файл:

      /etc/apache2/sites-available/example.com.conf

      <VirtualHost *:80>
          ServerAdmin [email protected]
          ServerName example.com
          ServerAlias www.example.com
          DocumentRoot /var/www/example.com/html
          ErrorLog ${APACHE_LOG_DIR}/error.log
          CustomLog ${APACHE_LOG_DIR}/access.log combined
      </VirtualHost>
      

      Обратите внимание, что мы обновили DocumentRoot на адрес нашей новой директории, и ServerAdmin на адрес электронной почты, доступный для администратора example.com. Мы также добавили две директивы: ServerName, которая устанавливает базовое доменное имя, которое должно использоваться для хоста, а также ServerAlias, которая определяет другие имена, которые должны использоваться для отображения хоста так же, как и базовое доменное имя.

      Сохраните и закройте файл после внесения изменений.

      Теперь активируем профиль сайта с помощью утилиты a2ensite:

      • sudo a2ensite example.com.conf

      Деактивируем дефолтный сайт, определённый в 000-default.conf:

      • sudo a2dissite 000-default.conf

      Далее проверим наши настройки на наличие ошибок:

      • sudo apache2ctl configtest

      Вы должны увидеть следующий вывод:

      Вывод

      Syntax OK

      Перезапустите Apache для применения внесённых изменений:

      • sudo systemctl restart apache2

      Теперь Apache должен работать с вашим доменным именем. Вы можете проверить это введя http://example.com в вашем браузере, где в результате вы должны увидеть что-то в этом роде:

      Успешная работа Apache

      Шаг 6 - Важные файлы и директории Apache

      Теперь, когда вы знаете, как управлять сервисом Apache, вам стоит ознакомиться с важными файлами и директориями Apache.

      Контент

      • /var/www/html: фактический веб-контент, который по умолчанию состоит только из дефолтной страницы Apache, которую мы видели ранее, хранится в директории /var/www/html. Это может быть изменено в конфигурационных файлах Apache.

      Конфигурация сервера

      • /etc/apache2: это конфигурационная директория Apache. Все файлы конфигурации Apache находятся здесь.
      • /etc/apache2/apache2.conf: главный конфигурационный файл Apache. Изменения в этом файле влияют на глобальную конфигурацию Apache. Этот файл отвечает за загрузку многих других файлов из конфигурационной директории.
      • /etc/apache2/ports.conf: этот файл определяет порты, которые Apache будет слушать. По умолчанию Apache слушает порт 80, а также порт 443 при условии, что модуль для работы с SSL включен.
      • /etc/apache2/sites-available/: в этой директории хранятся файлы виртуальных хостов. Apache не использует файлы из этой директории, если ссылки на них нет в директории sites-enabled. Обычно настройка всех файлов виртуальных хостов осуществляется в этой директории, а активация хоста происходит путём создания ссылки в другой директории командой a2ensite.
      • /etc/apache2/sites-enabled/: директория, в которой хранятся активированные виртуальные хосты. Обычно это делается путём создания ссылки на файл конфигурации хоста из директории sites-available с помощью команды a2ensite. Apache читает конфигурационный файлы и ссылки из этой директории при запуске или перезапуске.
      • /etc/apache2/conf-available/, /etc/apache2/conf-enabled/: эти директории связаны друг с другом так же, как и sites-available и sites-enabled связаны друг с другом, но используются для хранения фрагментов конфигурации, которые не принадлежат виртуальным хостам. Файлы в директории conf-available могут быть включены командой a2enconf и выключены командой a2disconf.
      • /etc/apache2/mods-available/, /etc/apache2/mods-enabled/: эти директории содержат, соответственно, доступные и активные модули. Файлы, оканчивающиеся на .load, содержат фрагменты для загрузки конкретных модулей, а файлы, оканчивающиеся на .conf, содержат настройки этих модулей. Модули можно активировать командой a2enmod и деактивировать командой a2dismod.

      Серверные логи

      • /var/log/apache2/access.log: по умолчанию каждый запрос к вашему веб-серверу записывается в этом файле, если только Apache не настроен на другое поведение.
      • /var/log/apache2/error.log: по умолчанию все ошибки записываются в этот файл. Директива LogLevel в конфигурации Apache определяет, насколько детальными должны быть записи об ошибках.

      Заключение

      Теперь, когда ваш веб-сервер установлен, у вас есть множество вариантов того, что делать дальше. Если вы хотите построить более полный стек приложений, вы можете ознакомиться с нашим руководством по установке и настройке стека LAMP на Ubuntu 18.04.



      Source link

      How To Install Linux, Apache, MariaDB, PHP (LAMP) stack on Debian 9


      Introduction

      A “LAMP” stack is a group of open source software that is typically installed together to enable a server to host dynamic websites and web apps. This term is actually an acronym which represents the Linux operating system, with the Apache web server. The site data is stored in a MariaDB database, and dynamic content is processed by PHP.

      In this guide, we will install a LAMP stack on a Debian 9 server.

      Prerequisites

      In order to complete this tutorial, you will need to have a Debian 9 server with a non-root sudo-enabled user account and a basic firewall. This can be configured using our initial server setup guide for Debian 9.

      Step 1 — Installing Apache and Updating the Firewall

      The Apache web server is among the most popular web servers in the world. It’s well-documented and has been in wide use for much of the history of the web, which makes it a great default choice for hosting a website.

      Install Apache using Debian’s package manager, apt:

      • sudo apt update
      • sudo apt install apache2

      Since this is a sudo command, these operations are executed with root privileges. It will ask you for your regular user’s password to verify your intentions.

      Once you’ve entered your password, apt will tell you which packages it plans to install and how much extra disk space they’ll take up. Press Y and hit ENTER to continue, and the installation will proceed.

      Next, assuming that you have followed the initial server setup instructions by installing and enabling the UFW firewall, make sure that your firewall allows HTTP and HTTPS traffic.

      When installed on Debian 9, UFW comes loaded with app profiles which you can use to tweak your firewall settings. View the full list of application profiles by running:

      The WWW profiles are used to manage ports used by web servers:

      Output

      Available applications: . . . WWW WWW Cache WWW Full WWW Secure . . .

      If you inspect the WWW Full profile, it shows that it enables traffic to ports 80 and 443:

      • sudo ufw app info "WWW Full"

      Output

      Profile: WWW Full Title: Web Server (HTTP,HTTPS) Description: Web Server (HTTP,HTTPS) Ports: 80,443/tcp

      Allow incoming HTTP and HTTPS traffic for this profile:

      • sudo ufw allow in “WWW Full”

      You can do a spot check right away to verify that everything went as planned by visiting your server's public IP address in your web browser:

      http://your_server_ip
      

      You will see the default Debian 9 Apache web page, which is there for informational and testing purposes. It should look something like this:

      Debian 9 Apache default

      If you see this page, then your web server is now correctly installed and accessible through your firewall.

      If you do not know what your server's public IP address is, there are a number of ways you can find it. Usually, this is the address you use to connect to your server through SSH.

      There are a few different ways to do this from the command line. First, you could use the iproute2 tools to get your IP address by typing this:

      • ip addr show eth0 | grep inet | awk '{ print $2; }' | sed 's//.*$//'

      This will give you two or three lines back. They are all correct addresses, but your computer may only be able to use one of them, so feel free to try each one.

      An alternative method is to use the curl utility to contact an outside party to tell you how it sees your server. This is done by asking a specific server what your IP address is:

      • sudo apt install curl
      • curl http://icanhazip.com

      Regardless of the method you use to get your IP address, type it into your web browser's address bar to view the default Apache page.

      Step 2 — Installing MariaDB

      Now that you have your web server up and running, it is time to install MariaDB. MariaDB is a database management system. Basically, it will organize and provide access to databases where your site can store information.

      MariaDB is a community-built fork of MySQL. In Debian 9, the default MySQL server is MariaDB 10.1, and the mysql-server package, which is normally used to install MySQL, is a transitional package that will actually install MariaDB. However, it’s recommended that you install MariaDB using the program’s actual package, mariadb-server.

      Again, use apt to acquire and install this software:

      • sudo apt install mariadb-server

      Note: In this case, you do not have to run sudo apt update prior to the command. This is because you recently ran it in the commands above to install Apache, and the package index on your computer should already be up-to-date.

      This command, too, will show you a list of the packages that will be installed, along with the amount of disk space they'll take up. Enter Y to continue.

      When the installation is complete, run a simple security script that comes pre-installed with MariaDB which will remove some insecure default settings and lock down access to your database system. Start the interactive script by running:

      • sudo mysql_secure_installation

      This will take you through a series of prompts where you can make some changes to your MariaDB installation’s security options. The first prompt will ask you to enter the current database root password. This is an administrative account in MariaDB that has increased privileges. Think of it as being similar to the root account for the server itself (although the one you are configuring now is a MariaDB-specific account). Because you just installed MariaDB and haven’t made any configuration changes yet, this password will be blank, so just press ENTER at the prompt.

      The next prompt asks you whether you'd like to set up a database root password. Type N and then press ENTER. In Debian, the root account for MariaDB is tied closely to automated system maintenance, so we should not change the configured authentication methods for that account. Doing so would make it possible for a package update to break the database system by removing access to the administrative account. Later, we will cover how to optionally set up an additional administrative account for password access if socket authentication is not appropriate for your use case.

      From there, you can press Y and then ENTER to accept the defaults for all the subsequent questions. This will remove some anonymous users and the test database, disable remote root logins, and load these new rules so that MariaDB immediately respects the changes you have made.

      In new installs on Debian systems, the root MariaDB user is set to authenticate using the unix_socket plugin by default rather than with a password. This allows for some greater security and usability in many cases, but it can also complicate things when you need to allow an external program (e.g., phpMyAdmin) administrative rights.

      Because the server uses the root account for tasks like log rotation and starting and stopping the server, it is best not to change the root account's authentication details. Changing the account credentials in the /etc/mysql/debian.cnf may work initially, but package updates could potentially overwrite those changes. Instead of modifying the root account, the package maintainers recommend creating a separate administrative account if you need to set up password-based access.

      To do so, we will be creating a new account called admin with the same capabilities as the root account, but configured for password authentication. To do this, open up the MariaDB prompt from your terminal:

      Now, we can create a new user with root privileges and password-based access. Change the username and password to match your preferences:

      • GRANT ALL ON *.* TO 'admin'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;

      Flush the privileges to ensure that they are saved and available in the current session:

      Following this, exit the MariaDB shell:

      Now, any time you want to access your database as your new administrative user, you’ll need to authenticate as that user with the password you just set using the following command:

      At this point, your database system is set up and you can move on to installing PHP, the final component of the LAMP stack.

      Step 3 — Installing PHP

      PHP is the component of your setup that will process code to display dynamic content. It can run scripts, connect to your MariaDB databases to get information, and hand the processed content over to your web server to display.

      Once again, leverage the apt system to install PHP. In addition, include some helper packages this time so that PHP code can run under the Apache server and talk to your MariaDB database:

      • sudo apt install php libapache2-mod-php php-mysql

      This should install PHP without any problems. We'll test this in a moment.

      In most cases, you will want to modify the way that Apache serves files when a directory is requested. Currently, if a user requests a directory from the server, Apache will first look for a file called index.html. We want to tell the web server to prefer PHP files over others, so make Apache look for an index.php file first.

      To do this, type this command to open the dir.conf file in a text editor with root privileges:

      • sudo nano /etc/apache2/mods-enabled/dir.conf

      It will look like this:

      /etc/apache2/mods-enabled/dir.conf

      <IfModule mod_dir.c>
          DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm
      </IfModule>
      

      Move the PHP index file (highlighted above) to the first position after the DirectoryIndex specification, like this:

      /etc/apache2/mods-enabled/dir.conf

      <IfModule mod_dir.c>
          DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
      </IfModule>
      

      When you are finished, save and close the file by pressing CTRL+X. Confirm the save by typing Y and then hit ENTER to verify the file save location.

      After this, restart the Apache web server in order for your changes to be recognized. Do this by typing this:

      • sudo systemctl restart apache2

      You can also check on the status of the apache2 service using systemctl:

      • sudo systemctl status apache2

      Sample Output

      ● apache2.service - The Apache HTTP Server Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled) Active: active (running) since Tue 2018-09-04 18:23:03 UTC; 9s ago Process: 22209 ExecStop=/usr/sbin/apachectl stop (code=exited, status=0/SUCCESS) Process: 22216 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS) Main PID: 22221 (apache2) Tasks: 6 (limit: 4915) CGroup: /system.slice/apache2.service ├─22221 /usr/sbin/apache2 -k start ├─22222 /usr/sbin/apache2 -k start ├─22223 /usr/sbin/apache2 -k start ├─22224 /usr/sbin/apache2 -k start ├─22225 /usr/sbin/apache2 -k start └─22226 /usr/sbin/apache2 -k start

      To enhance the functionality of PHP, you have the option to install some additional modules. To see the available options for PHP modules and libraries, pipe the results of apt search into less, a pager which lets you scroll through the output of other commands:

      Use the arrow keys to scroll up and down, and press Q to quit.

      The results are all optional components that you can install. It will give you a short description for each:

      Output

      Sorting... Full Text Search... bandwidthd-pgsql/stable 2.0.1+cvs20090917-10 amd64 Tracks usage of TCP/IP and builds html files with graphs bluefish/stable 2.2.9-1+b1 amd64 advanced Gtk+ text editor for web and software development cacti/stable 0.8.8h+ds1-10 all web interface for graphing of monitoring systems cakephp-scripts/stable 2.8.5-1 all rapid application development framework for PHP (scripts) ganglia-webfrontend/stable 3.6.1-3 all cluster monitoring toolkit - web front-end haserl/stable 0.9.35-2+b1 amd64 CGI scripting program for embedded environments kdevelop-php-docs/stable 5.0.3-1 all transitional package for kdevelop-php kdevelop-php-docs-l10n/stable 5.0.3-1 all transitional package for kdevelop-php-l10n … :

      To learn more about what each module does, you could search the internet for more information about them. Alternatively, look at the long description of the package by typing:

      There will be a lot of output, with one field called Description which will have a longer explanation of the functionality that the module provides.

      For example, to find out what the php-cli module does, you could type this:

      Along with a large amount of other information, you'll find something that looks like this:

      Output

      … Description: command-line interpreter for the PHP scripting language (default) This package provides the /usr/bin/php command interpreter, useful for testing PHP scripts from a shell or performing general shell scripting tasks. . PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source general-purpose scripting language that is especially suited for web development and can be embedded into HTML. . This package is a dependency package, which depends on Debian's default PHP version (currently 7.0). …

      If, after researching, you decide you would like to install a package, you can do so by using the apt install command like you have been doing for the other software.

      If you decided that php-cli is something that you need, you could type:

      If you want to install more than one module, you can do that by listing each one, separated by a space, following the apt install command, like this:

      • sudo apt install package1 package2 ...

      At this point, your LAMP stack is installed and configured. Before making any more changes or deploying an application, though, it would be helpful to proactively test out your PHP configuration in case there are any issues that should be addressed.

      Step 4 — Testing PHP Processing on your Web Server

      In order to test that your system is configured properly for PHP, create a very basic PHP script called info.php. In order for Apache to find this file and serve it correctly, it must be saved to a very specific directory called the web root.

      In Debian 9, this directory is located at /var/www/html/. Create the file at that location by running:

      • sudo nano /var/www/html/info.php

      This will open a blank file. Add the following text, which is valid PHP code, inside the file:

      /var/www/html/info.php

      <?php
      phpinfo();
      ?>
      

      When you are finished, save and close the file.

      Now you can test whether your web server is able to correctly display content generated by this PHP script. To try this out, visit this page in your web browser. You'll need your server's public IP address again.

      The address you will want to visit is:

      http://your_server_ip/info.php
      

      The page that you come to should look something like this:

      Debian 9 default PHP info

      This page provides some basic information about your server from the perspective of PHP. It is useful for debugging and to ensure that your settings are being applied correctly.

      If you can see this page in your browser, then your PHP is working as expected.

      You probably want to remove this file after this test because it could actually give information about your server to unauthorized users. To do this, run the following command:

      • sudo rm /var/www/html/info.php

      You can always recreate this page if you need to access the information again later.

      Conclusion

      Now that you have a LAMP stack installed, you have many choices for what to do next. Basically, you've installed a platform that will allow you to install most kinds of websites and web software on your server.



      Source link

      How To Install the Apache Web Server on Debian 9


      Introduction

      The Apache HTTP server is the most widely-used web server in the world. It provides many powerful features including dynamically loadable modules, robust media support, and extensive integration with other popular software.

      In this guide, we’ll explain how to install an Apache web server on your Debian 9 server.

      Prerequisites

      Before you begin this guide, you should have a regular, non-root user with sudo privileges configured on your server. Additionally, you will need to enable a basic firewall to block non-essential ports. You can learn how to configure a regular user account and set up a firewall for your server by following our initial server setup guide for Debian 9.

      When you have an account available, log in as your non-root user to begin.

      Step 1 — Installing Apache

      Apache is available within Debian’s default software repositories, making it possible to install it using conventional package management tools.

      Let’s begin by updating the local package index to reflect the latest upstream changes:

      Then, install the apache2 package:

      After confirming the installation, apt will install Apache and all required dependencies.

      Step 2 — Adjusting the Firewall

      Before testing Apache, it's necessary to modify the firewall settings to allow outside access to the default web ports. Assuming that you followed the instructions in the prerequisites, you should have a UFW firewall configured to restrict access to your server.

      During installation, Apache registers itself with UFW to provide a few application profiles that can be used to enable or disable access to Apache through the firewall.

      List the ufw application profiles by typing:

      You will see a list of the application profiles:

      Output

      Available applications: AIM Bonjour CIFS . . . WWW WWW Cache WWW Full WWW Secure . . .

      The Apache profiles begin with WWW:

      • WWW: This profile opens only port 80 (normal, unencrypted web traffic)
      • WWW Cache: This profile opens only port 8080 (sometimes used for caching and web proxies)
      • WWW Full: This profile opens both port 80 (normal, unencrypted web traffic) and port 443 (TLS/SSL encrypted traffic)
      • WWW Secure: This profile opens only port 443 (TLS/SSL encrypted traffic)

      It is recommended that you enable the most restrictive profile that will still allow the traffic you've configured. Since we haven't configured SSL for our server yet in this guide, we will only need to allow traffic on port 80:

      You can verify the change by typing:

      You should see HTTP traffic allowed in the displayed output:

      Output

      Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere WWW ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6) WWW (v6) ALLOW Anywhere (v6)

      As you can see, the profile has been activated to allow access to the web server.

      Step 3 — Checking your Web Server

      At the end of the installation process, Debian 9 starts Apache. The web server should already be up and running.

      Check with the systemd init system to make sure the service is running by typing:

      • sudo systemctl status apache2

      Output

      ● apache2.service - The Apache HTTP Server Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2018-09-05 19:21:48 UTC; 13min ago Main PID: 12849 (apache2) CGroup: /system.slice/apache2.service ├─12849 /usr/sbin/apache2 -k start ├─12850 /usr/sbin/apache2 -k start └─12852 /usr/sbin/apache2 -k start Sep 05 19:21:48 apache systemd[1]: Starting The Apache HTTP Server... Sep 05 19:21:48 apache systemd[1]: Started The Apache HTTP Server.

      As you can see from this output, the service appears to have started successfully. However, the best way to test this is to request a page from Apache.

      You can access the default Apache landing page to confirm that the software is running properly through your IP address. If you do not know your server's IP address, you can get it a few different ways from the command line.

      Try typing this at your server's command prompt:

      You will get back a few addresses separated by spaces. You can try each in your web browser to see if they work.

      An alternative is using the curl tool, which should give you your public IP address as seen from another location on the internet.

      First, install curl using apt:

      Then, use curl to retrieve icanhazip.com using IPv4:

      When you have your server's IP address, enter it into your browser's address bar:

      http://your_server_ip
      

      You should see the default Debian 9 Apache web page:

      Apache default page

      This page indicates that Apache is working correctly. It also includes some basic information about important Apache files and directory locations.

      Step 4 — Managing the Apache Process

      Now that you have your web server up and running, let's go over some basic management commands.

      To stop your web server, type:

      • sudo systemctl stop apache2

      To start the web server when it is stopped, type:

      • sudo systemctl start apache2

      To stop and then start the service again, type:

      • sudo systemctl restart apache2

      If you are simply making configuration changes, Apache can often reload without dropping connections. To do this, use this command:

      • sudo systemctl reload apache2

      By default, Apache is configured to start automatically when the server boots. If this is not what you want, disable this behavior by typing:

      • sudo systemctl disable apache2

      To re-enable the service to start up at boot, type:

      • sudo systemctl enable apache2

      Apache should now start automatically when the server boots again.

      When using the Apache web server, you can use virtual hosts (similar to server blocks in Nginx) to encapsulate configuration details and host more than one domain from a single server. We will set up a domain called example.com, but you should replace this with your own domain name. To learn more about setting up a domain name with DigitalOcean, see our Introduction to DigitalOcean DNS.

      Apache on Debian 9 has one server block enabled by default that is configured to serve documents from the /var/www/html directory. While this works well for a single site, it can become unwieldy if you are hosting multiple sites. Instead of modifying /var/www/html, let's create a directory structure within /var/www for our example.com site, leaving /var/www/html in place as the default directory to be served if a client request doesn't match any other sites.

      Create the directory for example.com as follows, using the -p flag to create any necessary parent directories:

      sudo mkdir -p /var/www/example.com/html
      

      Next, assign ownership of the directory with the $USER environmental variable:

      • sudo chown -R $USER:$USER /var/www/example.com/html

      The permissions of your web roots should be correct if you haven't modified your unmask value, but you can make sure by typing:

      • sudo chmod -R 755 /var/www/example.com

      Next, create a sample index.html page using nano or your favorite editor:

      • nano /var/www/example.com/html/index.html

      Inside, add the following sample HTML:

      /var/www/example.com/html/index.html

      <html>
          <head>
              <title>Welcome to Example.com!</title>
          </head>
          <body>
              <h1>Success!  The example.com server block is working!</h1>
          </body>
      </html>
      

      Save and close the file when you are finished.

      In order for Apache to serve this content, it's necessary to create a virtual host file with the correct directives. Instead of modifying the default configuration file located at /etc/apache2/sites-available/000-default.conf directly, let's make a new one at /etc/apache2/sites-available/example.com.conf:

      • sudo nano /etc/apache2/sites-available/example.com.conf

      Paste in the following configuration block, which is similar to the default, but updated for our new directory and domain name:

      /etc/apache2/sites-available/example.com.conf

      <VirtualHost *:80>
          ServerAdmin [email protected]
          ServerName example.com
          ServerAlias www.example.com
          DocumentRoot /var/www/example.com/html
          ErrorLog ${APACHE_LOG_DIR}/error.log
          CustomLog ${APACHE_LOG_DIR}/access.log combined
      </VirtualHost>
      

      Notice that we've updated the DocumentRoot to our new directory and ServerAdmin to an email that the example.com site administrator can access. We've also added two directives: ServerName, which establishes the base domain that should match for this virtual host definition, and ServerAlias, which defines further names that should match as if they were the base name.

      Save and close the file when you are finished.

      Let's enable the file with the a2ensite tool:

      • sudo a2ensite example.com.conf

      Disable the default site defined in 000-default.conf:

      • sudo a2dissite 000-default.conf

      Next, let's test for configuration errors:

      • sudo apache2ctl configtest

      You should see the following output:

      Output

      Syntax OK

      Restart Apache to implement your changes:

      • sudo systemctl restart apache2

      Apache should now be serving your domain name. You can test this by navigating to http://example.com, where you should see something like this:

      Apache virtual host example

      Step 6 – Getting Familiar with Important Apache Files and Directories

      Now that you know how to manage the Apache service itself, you should take a few minutes to familiarize yourself with a few important directories and files.

      Content

      • /var/www/html: The actual web content, which by default only consists of the default Apache page you saw earlier, is served out of the /var/www/html directory. This can be changed by altering Apache configuration files.

      Server Configuration

      • /etc/apache2: The Apache configuration directory. All of the Apache configuration files reside here.
      • /etc/apache2/apache2.conf: The main Apache configuration file. This can be modified to make changes to the Apache global configuration. This file is responsible for loading many of the other files in the configuration directory.
      • /etc/apache2/ports.conf: This file specifies the ports that Apache will listen on. By default, Apache listens on port 80 and additionally listens on port 443 when a module providing SSL capabilities is enabled.
      • /etc/apache2/sites-available/: The directory where per-site virtual hosts can be stored. Apache will not use the configuration files found in this directory unless they are linked to the sites-enabled directory. Typically, all server block configuration is done in this directory, and then enabled by linking to the other directory with the a2ensite command.
      • /etc/apache2/sites-enabled/: The directory where enabled per-site virtual hosts are stored. Typically, these are created by linking to configuration files found in the sites-available directory with the a2ensite. Apache reads the configuration files and links found in this directory when it starts or reloads to compile a complete configuration.
      • /etc/apache2/conf-available/, /etc/apache2/conf-enabled/: These directories have the same relationship as the sites-available and sites-enabled directories, but are used to store configuration fragments that do not belong in a virtual host. Files in the conf-available directory can be enabled with the a2enconf command and disabled with the a2disconf command.
      • /etc/apache2/mods-available/, /etc/apache2/mods-enabled/: These directories contain the available and enabled modules, respectively. Files in ending in .load contain fragments to load specific modules, while files ending in .conf contain the configuration for those modules. Modules can be enabled and disabled using the a2enmod and a2dismod command.

      Server Logs

      • /var/log/apache2/access.log: By default, every request to your web server is recorded in this log file unless Apache is configured to do otherwise.
      • /var/log/apache2/error.log: By default, all errors are recorded in this file. The LogLevel directive in the Apache configuration specifies how much detail the error logs will contain.

      Conclusion

      Now that you have your web server installed, you have many options for the type of content you can serve and the technologies you can use to create a richer experience.

      If you'd like to build out a more complete application stack, you can look at this article on how to configure a LAMP stack on Debian 9.



      Source link