Что такое apache и как он работает

What they are/How to use them

files (or «distributed configuration files»)
provide a way to make configuration changes on a per-directory basis. A
file, containing one or more configuration directives, is placed in a
particular document directory, and the directives apply to that
directory, and all subdirectories thereof.

Note:

If you want to call your file something
else, you can change the name of the file using the directive. For example,
if you would rather call the file then you
can put the following in your server configuration file:

AccessFileName ".config"

In general, files use the same syntax as
the . What you can put in these files is determined by the
directive. This
directive specifies, in categories, what directives will be
honored if they are found in a file. If a
directive is permitted in a file, the
documentation for that directive will contain an Override section,
specifying what value must be in in order for that
directive to be permitted.

For example, if you look at the documentation for the
directive, you will find that it is permitted in
files. (See the Context line in the directive summary.) The line reads
. Thus, you must have at least
in order for this directive to be
honored in files.

What they are/How to use them

files (or «distributed configuration files»)
provide a way to make configuration changes on a per-directory basis. A
file, containing one or more configuration directives, is placed in a
particular document directory, and the directives apply to that
directory, and all subdirectories thereof.

Note:

If you want to call your file something
else, you can change the name of the file using the directive. For example,
if you would rather call the file then you
can put the following in your server configuration file:

AccessFileName ".config"

In general, files use the same syntax as
the . What you can put in these files is determined by the
directive. This
directive specifies, in categories, what directives will be
honored if they are found in a file. If a
directive is permitted in a file, the
documentation for that directive will contain an Override section,
specifying what value must be in in order for that
directive to be permitted.

For example, if you look at the documentation for the
directive, you will find that it is permitted in
files. (See the Context line in the directive summary.) The line reads
. Thus, you must have at least
in order for this directive to be
honored in files.

Troubleshooting

See the status of the Apache daemon with systemctl.

Apache logs can be found in

/run/httpd not being created at boot

If as the root user complains about «unsafe path transition», check ownership of your root directory.

ls -la /
chown root:root /

Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe.

If when loading the fails, and you get an error like this in the journal:

Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe.  You need to recompile PHP.

This is because PHP includes support for a module that is not threadsafe, and you are trying to use a threaded MPM. One solution to fix this is to use a non-threaded MPM. Try replacing with :

/etc/httpd/conf/httpd.conf
LoadModule mpm_event_module modules/mod_mpm_event.so
LoadModule mpm_prefork_module modules/mod_mpm_prefork.so

and restart .

AH00534: httpd: Configuration error: No MPM loaded.

You might encounter this error after a recent upgrade. This is only the result of a recent change in that you might not have reproduced in your local configuration.
To fix it, uncomment the following line.

/etc/httpd/conf/httpd.conf
LoadModule mpm_prefork_module modules/mod_mpm_prefork.so

and restart .

AH00072: make_sock: could not bind to address

This can be caused by multiple things. Most common issue being that something is already listening on a given port, check via netstat that this is not happening:

# netstat -lnp | grep -e :80 -e :443

If you get any output, stop the given service that’s taking up the port or kill the runaway process that is causing the port to be bound, and try again.

Another issue could be that Apache is not starting as root for some reason — try starting it manually and see if you still get the AH0072 error.

# httpd -k start

Finally, you can also have an error with your config and you are listening twice on the given port. Following is an example of a bad config that will trigger this issue:

Listen 0.0.0.0:80
Listen :80

AH01071: Got error ‘Primary script unknown’

This can be caused by in the php-fpm systemd unit file if you are serving files in such as in a virtual host environment. You can disable this feature by and restarting php-fpm. Alternatively, move your document root.

Changing the max_execution_time in php.ini has no effect

If you changed the in to a value greater than 30 (seconds), you may still get a response from Apache after 30 seconds. To solve this, add a directive to your http configuration right before the block:

/etc/httpd/conf/httpd.conf
ProxyTimeout 300

and restart .

PHP-FPM: errors are not being logged separately per virtual host

If you have multiple virtual hosts, it may be desirable to have each of them output their error logs to separate files (using the ErrorLog Apache directive). If this is not working for you, confirm that PHP-FPM is configured to log errors to syslog:

/etc/php/php-fpm.conf
error_log = syslog

It’s also possible that the pool configuration is overriding it. Ensure the following line is commented out:

/etc/php/php-fpm.d/www.conf
;php_admin_value = /var/log/fpm-php.www.log

Проверяем доступность страницы с других компьютеров и настраиваем брандмауэр

Снова пробуем открыть знакомую нам страницу http://192.168.0.189 (у вас цифры другие) но уже с любого другого компьютера в локальной сети.  

Если вместо знакомой страницы вы увидели «Не удается получить доступ к сайту» или аналогичное сообщение — выполним настроку брандмауэра. Для этого возвращаемся на тот компьютер, где установлен Apache, заходим в «Панель управления» — «Система и безопасность» — «Брандмауэр Windows» и в левой части экрана щелкаем на «Дополнительные параметры

Кликаем на раздел «Правила для входящих подключений», затем в правой части окна «Создать правило»

Выбираем «Для порта» — Далее, Протокол TCP, Опреленные локальные порты: 80, Далее 

Устанавливаем «Разрешить подключение» — Далее, 

Ставим все три галочки

Указываем произвольное имя, например «Веб сервер 80 порт для 1С». Готово.

Снова идем на другие компьютеры и убеждаемся, что теперь по IP адресу http://192.168.0.189 броузер показывает знакомую нам страницу It Works

Rewrite Rules in .htaccess files

When using in
files, be aware that the per-directory context
changes things a bit. In particular, rules are taken to be relative to
the current directory, rather than being the original requested URI.
Consider the following examples:

# In httpd.conf
RewriteRule "^/images/(.+)\.jpg" "/images/$1.png"

# In .htaccess in root dir
RewriteRule "^images/(.+)\.jpg" "images/$1.png"

# In .htaccess in images/
RewriteRule "^(.+)\.jpg" "$1.png"

In a in your document directory, the leading
slash is removed from the value supplied to , and in the
subdirectory, is removed from
it. Thus, your regular expression needs to omit that portion as
well.

Apache и другие веб-сервера

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

Apache или NGINX

Nginx произносится как Engine-X, это более новое веб-серверное программное обеспечение с первым релизом в 2004 году. Как на сегодня он добился большой популярности среди владельцев сайтов. Nginx был создан для решения так называемой проблемы c10k – проблемы 10 тысяч соединений, что означает, что веб-сервера, использующие потоки не могут обрабатывать запросы пользователей более, чем с 10 000 подключений одновременно.

  1. Так как Apache использует структуру основанную на потоках, владельцы сайтов с высоким трафиком могли столкнуться с проблемой производительности. Nginx один из веб-серверов, который был нацелен на решение проблемы c10k и возможно это одно из самых успешных решений.
  2. Nginx имеет событийно ориентированную архитектуру, которая не создаёт новый процесс для каждого запроса. Вместо этого он обрабатывает каждый входящий запрос в едином потоке. Этот главный процесс управляет несколькими рабочими процессами, которые выполняют непосредственную обработку запросов. Модель Nginx, основанная на событиях распространяет запросы пользователей среди рабочих процессов эффективным путём, что приводит к лучшей масштабируемости.
  3. Если вам нужно обслуживание сайта с высокой посещаемостью, то Nginx – отличный выбор, поскольку он может сделать это, затратив минимальные ресурсы. И не случайно он используется сайтами с большим количеством показов, такими как: Netflix, Hulu, Pinterest и Airbnb.
  4. Однако для мелких и средних игроков, Apache имеет несколько преимуществ в сравнении с Nginx, среди которых: более простая настройка, множество модулей и среда дружественная для начинающих.

Apache или Tomcat

Tomcat – это веб-сервер также разработанных Apache Software Foundation, поэтому его официальное название Apache Tomcat. Это тоже HTTP-сервер, однако он обрабатывает приложения Java вместо статических сайтов. Tomcat может запускать несколько Java спецификаций, таких как: Java Servlet, Java Server Pages (JSP), Java EL и WebSocket.

  1. Tomcat был разработан специально для приложений на Java, в то время как Apache позиционируется как HTTP-сервер. Вы можете использовать Apache совместно с другими языками программирования (PHP, Python, Perl и т.д.) с помощью специального модуля Apache (mod_php, mod_python, mod_perl и др.).
  2. Хотя вы и можете использовать сервер Tomcat для статических веб-страниц, но это будет менее эффективно, чем использование Apache. Например, Tomcat заранее загружает виртуальную машину Java и другие Java-библиотеки, которые могут быть ненужными для работы вашего сайта.
  3. Tomcat также хуже настраиваемых в сравнении с другими веб-серверами. Например, для запуска WordPress, лучшим выбором будет стандартный HTTP-сервер, такой как Apache или NGINX.

How the server selects the proper name-based virtual host

It is important to recognize that the first step in name-based virtual
host resolution is IP-based resolution. Name-based virtual host
resolution only chooses the most appropriate name-based virtual host
after narrowing down the candidates to the best IP-based match. Using a wildcard (*)
for the IP address in all of the VirtualHost directives makes this
IP-based mapping irrelevant.

When a request arrives, the server will find the best (most specific) matching
argument based on
the IP address and port used by the request. If there is more than one virtual host
containing this best-match address and port combination, Apache will further
compare the and directives to the server name
present in the request.

If you omit the
directive from any name-based virtual host, the server will default
to a fully qualified domain name (FQDN) derived from the system hostname.
This implicitly set server name can lead to counter-intuitive virtual host
matching and is discouraged.

ШАГ 1 развертывание дистрибутива Apache

Сборка Apache 2.4.23 x64 от Apache Haus поставляется в zip архиве и не имеет инсталлятора Windows, поэтому считается портативным (portable) вариантом дистрибутива Apache. Portable версия имеет ряд удобств и позволяет разместить дистрибутив в любом каталоге файловой системы и самостоятельно настроить запуск Apache так как вам нужно.

Рекомендую для разрешения дистрибутива Apache выбрать каталог, путь к которому будет содержать только EN символы и не будет иметь пробелов, т.к. этот путь станет для Apache значением ServerRoot директивы, в которой задается домашняя директория WEB сервера.

В примерах этой статьи и скринкаста дистрибутив Apache будет развернут в директорию «Z:\WebDevelopment\Apache24» и, соответственно, ServerRoot директива будет определена как «Z:/WebDevelopment/Apache24».

Формат значения пути в директиве ServerRoot следующий:

  • слеши прямые и одинарные;
  • завершающего слеша нет;
  • если есть пробелы, то путь должен быть в кавычках («path_to»),
  • на Linux значение чувствительно к регистру символов.

Структура дистрибутива Apache

Сборка Apache 2.4.23 x64 от Apache Haus имеет следующую структуру каталогов:

|Apache24....................Домашняя директория Apache - ServerRoot
    |-- bin..................Директория с бинарниками Apache
    |    `-- ...
    |    `-- ApacheMonitor.exe...Программа монитор для управления Apache как Windows службой
    |    `-- httpd.exe...........Главный исполняемый файл web сервера Apache
    |    `-- ...
    |-- cgi-bin.......Директория обработчика для CGI program
    |-- conf..........Директория с конфигурационными файлами Apache
    |    `-- extra....Директория с дополнительными конфигами Apache, которые подключаются в httpd.conf
    |        |    `-- httpd-ahssl.conf
    |        |    `-- httpd-autoindex.conf
    |        |    `-- httpd-dav.conf
    |        |    `-- httpd-default.conf
    |        |    `-- httpd-deflate.conf
    |        |    `-- httpd-info.conf
    |        |    `-- httpd-languages.conf
    |        |    `-- httpd-manual.conf
    |        |    `-- httpd-mpm.conf
    |        |    `-- httpd-multilang-errordoc.conf
    |        |    `-- httpd-proxy-html.conf
    |        |    `-- httpd-ssl.conf
    |        |    `-- httpd-userdir.conf
    |        |    `-- httpd-vhosts.conf
    |    `-- original........Директория исходных конфигов от Apache, добавлена в сборку для справки
    |    `-- ssl.............Директория для SSL сертификатов
    |    `-- charset.conv....Конфиг установки кодировки, подключаются в httpd.conf
    |    `-- httpd.conf......Главный конфиг Apache в данной сборке от Apache Haus
    |    `-- magic...........Конфиг скриптов для модуля mime_magic
    |    `-- mime.types......Конфиг установки MIME типов
    |    `-- openssl.cnf.....Конфиг OpenSSL
    |-- error................Директория с конфигами страниц ошибок для Apache
    |-- htdocs...............Директория и хост по умолчанию с документацией от Apache Haus
    |-- icons................Директория с иконками
    |-- include..............Директория служебных скриптов Apache
    |-- lib..................Директория вспомогательных библиотек
    |-- logs.................Директория файлов журналов Apache
    |-- modules..............Директория модулей Apache
    |-- ABOUT_APACHE.txt
    |-- CHANGES.txt
    |-- INSTALL.txt
    |-- LICENSE.txt
    |-- NOTICE.txt
    |-- OPENSSL-NEWS.txt
    |-- OPENSSL-README.txt
    |-- README.txt
|-- readme_first.html......Краткий help от Apache Haus, лежит в корне zip архива

Данная сборка Apache 2.4.23 x64 от Apache Haus для Windows является полным дистрибутивом WEB сервера и содержит все необходимые исполняемые и конфигурационные файлы для полноценной работы Apache как веб сервера, включая и использование https соединения. Соответственно, установил эту сборку и настроив ее, вы получаете полный, со всеми модулями, web сервер Apache, который можете использовать не только для разработки и тестирования, но и для продуктивного хостинга сайтов на Windows.

В zip архиве данной сборки так же вложен файл readme_first.html, который содержит краткое описание компонентов данной сборки и их версий. Так же, в этом файле приведены краткие инструкции от Apache Haus по установке Apache, VC14, инсталляции Apache как системной службы и даны необходимые ссылки.

Types of Configuration Section Containers

There are two basic types of containers. Most containers are
evaluated for each request. The enclosed directives are applied only
for those requests that match the containers. The , , and

containers, on the other hand, are evaluated only at server startup
and restart. If their conditions are true at startup, then the
enclosed directives will apply to all requests. If the conditions are
not true, the enclosed directives will be ignored.

The directive
encloses directives that will only be applied if an appropriate
parameter is defined on the command line. For example,
with the following configuration, all requests will be redirected
to another site only if the server is started using
:

<IfDefine ClosedForNow>
    Redirect "/" "http://otherserver.example.com/"
</IfDefine>

The
directive is very similar, except it encloses directives that will
only be applied if a particular module is available in the server.
The module must either be statically compiled in the server, or it
must be dynamically compiled and its line must be earlier in the
configuration file. This directive should only be used if you need
your configuration file to work whether or not certain modules are
installed. It should not be used to enclose directives that you want
to work all the time, because it can suppress useful error messages
about missing modules.

In the following example, the directive will be
applied only if is available.

<IfModule mod_mime_magic.c>
    MimeMagicFile "conf/magic"
</IfModule>

The
directive is very similar to and , except it encloses directives that will
only be applied if a particular version of the server is executing. This
module is designed for
the use in test suites and large networks which have to
deal with different httpd versions and different configurations.

<IfVersion >= 2.4>
    # this happens only in versions greater or
    # equal 2.4.0.
</IfVersion>

Настройка HTTPS в Apache

Создание ключа и ssl-сертификата

  • Использование самоподписанных сертификатов хоть и защищает от пассивного прослушивания, тем не менее не гарантирует клиентам, что сервер является именно тем сервером, который им нужен. Преимуществом самоподписанных сертификатов является их бесплатность. Сертификат, подписанный компанией-сертификатором (Certificate authority), стоит денег.
  • Для создания ключа и сертификата вводим команду:
 openssl req -new -x509 -days 30 -keyout server.key -out server.pem
  • На вопрос «Enter PEM pass phrase:» отвечаем паролем, подтверждаем и запоминаем.
  • На все последующие вопросы отвечаем произвольно, можно просто щелкать по Enter, соглашаясь с предложенными вариантами, только на вопрос «Common Name (eg, YOUR name) []:» отвечаем именем сайта, для которого создаем сертификат, например www.example.com.
  • После ответа на все вопросы в директории должны появиться два новых файла — server.pem (ключ) и server.crt (сертификат).
  • Чтобы использовать сгенерированный ключ, нужно знать пароль, введённый нами, и Apache будет спрашивать его у нас при загрузке. Чтобы избавиться от подобной рутины:
 cp server.key{,.orig}
 openssl rsa -in server.key.orig -out server.key
 rm server.key.orig

Скопируем их в /etc/ssl и назначим файлу ключа права чтения только администратору:

 sudo cp server.pem /etc/ssl/certs/
 sudo cp server.key /etc/ssl/private/
 sudo chmod 0600 /etc/ssl/private/server.key

Настройка Apache

Для начала необходимо активировать mod_ssl:

 sudo a2enmod ssl

А затем включить настройки HTTPS сайта по умолчанию:

 sudo a2ensite default-ssl
  • Теперь необходимо отредактировать файл с настройками HTTPS сайта по умолчанию, указав в нём пути к вашим сертификатам. Сам файл называется (или ).
  • В этом файле рекомендуется после директивы
 SSLEngine on

добавить строчку

 SSLProtocol all -SSLv2

чтобы запретить использование устаревшего протокола SSLv2.
Дальше вам необходимо отредактировать параметры, ответственные за сертификаты.

 # Публичный сертификат сервера
 SSLCertificateFile    /etc/ssl/certs/server.pem
 # Приватный ключ сервера
 SSLCertificateKeyFile /etc/ssl/private/server.key

Теперь просто перезагрузите Apache:

 sudo service apache2 restart
  • И если все параметры указаны верно, ваши сайты станут доступны по HTTPS.
  • Протокол HTTPS работает по 443 порту, поэтому если сервер находится за шлюзом, то необходимо на нём пробросить данный порт.

Перенаправление HTTP запросов на HTTPS

Если вы хотите запретить использование HTTP, то самым разумным будет перенаправлять все HTTP запросы к страницам на их HTTPS адрес. Сделаем это с помощью mod_alias. Если он не включён — включаем:

 sudo a2enmod alias
 sudo service apache2 restart

Затем изменяем файл /etc/apache2/sites-enabled/000-default, отвечающий за виртуальный хост по умолчанию для HTTP запросов. В этот файл добавляем директиву

  • При этом все настройки директорий можно удалить, поскольку по HTTP на ваши сайты всё равно будет не попасть.
  • Всё, теперь ещё раз перезапустите Apache и убедитесь, что при заходе по HTTP вы автоматически перенаправляетесь на HTTPS-страницу.

Early Hints

An alternative to PUSHing resources is to send headers to the
client before the response is even ready. This uses the HTTP feature called «Early Hints» and
is described in RFC 8297.

In order to use this, you need to explicitly enable it on the server via

H2EarlyHints on

(It is not enabled by default since some older browser tripped on such responses.)

If this feature is on, you can use the directive to
trigger early hints and resource PUSHes:

<Location /xxx.html>
    H2PushResource /xxx.css
    H2PushResource /xxx.js
</Location>

This will send out a response to a client as soon
as the server starts processing the request. This may be much early than
the time the first response headers have been determined, depending on your web
application.

When (not) to use .htaccess files

In general, you should only use files when
you don’t have access to the main server configuration file. There is,
for example, a common misconception that user authentication should
always be done in files, and, in more recent years,
another misconception that directives
must go in files. This is simply not the
case. You can put user authentication configurations in the main server
configuration, and this is, in fact, the preferred way to do
things. Likewise, directives work better,
in many respects, in the main server configuration.

files should be used in a case where the
content providers need to make configuration changes to the server on a
per-directory basis, but do not have root access on the server system.
In the event that the server administrator is not willing to make
frequent configuration changes, it might be desirable to permit
individual users to make these changes in files
for themselves. This is particularly true, for example, in cases where
ISPs are hosting multiple user sites on a single machine, and want
their users to be able to alter their configuration.

However, in general, use of files should be
avoided when possible. Any configuration that you would consider
putting in a file, can just as effectively be
made in a section in your main server
configuration file.

There are two main reasons to avoid the use of
files.

The first of these is performance. When
is set to allow the use of files, httpd will
look in every directory for files. Thus,
permitting files causes a performance hit,
whether or not you actually even use them! Also, the
file is loaded every time a document is
requested.

Further note that httpd must look for files
in all higher-level directories, in order to have a full complement of
directives that it must apply. (See section on .) Thus, if a file is requested out of a
directory , httpd must look for the
following files:

And so, for each file access out of that directory, there are 4
additional file-system accesses, even if none of those files are
present. (Note that this would only be the case if
files were enabled for , which
is not usually the case.)

In the case of directives, in
context these regular expressions must be
re-compiled with every request to the directory, whereas in main
server configuration context they are compiled once and cached.
Additionally, the rules themselves are more complicated, as one must
work around the restrictions that come with per-directory context
and . Consult the for more
detail on this subject.

The second consideration is one of security. You are permitting
users to modify server configuration, which may result in changes over
which you have no control. Carefully consider whether you want to give
your users this privilege. Note also that giving users less
privileges than they need will lead to additional technical support
requests. Make sure you clearly tell your users what level of
privileges you have given them. Specifying exactly what you have set
to, and pointing them
to the relevant documentation, will save yourself a lot of confusion
later.

Note that it is completely equivalent to put a
file in a directory containing a
directive, and to put that same directive in a Directory section
in your main server
configuration:

file in :

Section from your
file

<Directory "/www/htdocs/example">
    AddType text/example ".exm"
</Directory>

However, putting this configuration in your server configuration
file will result in less of a performance hit, as the configuration is
loaded once when httpd starts, rather than every time a file is
requested.

The use of files can be disabled completely
by setting the
directive to :

Как работает веб-сервер Apache?

Хоть Apache и называется веб-сервер, но в реальном положении вещей он является не сервером, а программой, которая запускается на сервере. Его задача установить соединение между сервером и браузером посетителей (Firefox, Google Chrome, Safari и др.) при доставке файлов туда и обратно между ними (клиент-серверная структура). Apache – это кроссплатформенное программное обеспечение, что значит оно хорошо работает как на Unix, так и на Windows серверах.

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

Apache хорошо и удобно настраиваемый поскольку имеет модульную структуру. Модули позволяют администраторам сервера включать или выключать дополнительную функциональность. У Apache есть модули безопасности, кэширования, редактирования URL, аутентификации посредством пароля и другие. Вы можете установить свою собственную конфигурацию через файл .htaccess, который является файлом настроек для Apache и поддерживается всеми тарифными планами Hostinger.

Знаете ли вы, что в Hostinger есть специальные предложения? Посетите нашу страницу купонов и сэкономьте до 75%! Не стоит забывать, что это предложение ограничено во времени!

Graceful Stop

Signal: WINCH

The or signal causes
the parent process to advise the children to exit after
their current request (or to exit immediately if they’re not
serving anything). The parent will then remove its and cease listening on
all ports. The parent will continue to run, and monitor children
which are handling requests. Once all children have finalised
and exited or the timeout specified by the has been
reached, the parent will also exit. If the timeout is reached,
any remaining children will be sent the signal
to force them to exit.

A signal will immediately terminate the
parent process and all children when in the «graceful» state. However
as the will
have been removed, you will not be able to use
or to send this signal.

Clients, Servers, and URLs ¶

Addresses on the Web are expressed with URLs — Uniform Resource Locators
— which specify a protocol (e.g. ), a servername (e.g.
), a URL-path (e.g.
), and possibly a query
string (e.g. ) used to pass additional
arguments to the server.

A client (e.g., a web browser) connects to a server (e.g., your Apache HTTP Server),
with the specified protocol, and makes a request for a resource using the
URL-path.

The URL-path may represent any number of things on the server. It may
be a file (like ) a handler (like server-status) or some kind of program
file (like ). We’ll discuss this more below in
the section.

The server will send a response consisting of a status
code and, optionally, a response body.
The status code indicates whether the request was successful, and, if not, what
kind of error condition there was. This tells the client what it should
do with the response. You can read about the possible response codes in
HTTP
Server
wiki.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector