Arch linux apache php mysql

Содержание
  1. Apache HTTP Server
  2. Contents
  3. Installation
  4. Configuration
  5. Advanced options
  6. User directories
  7. Virtual hosts
  8. Managing many virtual hosts
  9. Extensions
  10. Using libphp
  11. Using apache2-mpm-worker and mod_fcgid
  12. Using php-fpm and mod_proxy_fcgi
  13. Test whether PHP works
  14. HTTP/2
  15. Troubleshooting
  16. Apache Status and Logs
  17. Error: PID file /run/httpd/httpd.pid not readable (yet?) after start
  18. /run/httpd not being created at boot
  19. Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe.
  20. AH00534: httpd: Configuration error: No MPM loaded.
  21. AH00072: make_sock: could not bind to address
  22. AH01071: Got error ‘Primary script unknown’
  23. Changing the max_execution_time in php.ini has no effect
  24. PHP-FPM: errors are not being logged separately per virtual host
  25. Apache HTTP Server (Русский)
  26. Contents
  27. Установка
  28. Настройка
  29. Дополнительные опции
  30. Пользовательские каталоги
  31. TLS/SSL
  32. Виртуальные хосты
  33. Управление большим количеством виртуальных хостов
  34. Расширения
  35. Дополнительные параметры
  36. Использование php5 c php-fpm и mod_proxy_fcgi
  37. Использование php5 c apache2-mpm-worker и mod_fcgid
  38. MySQL/MariaDB
  39. Решение проблем
  40. Просмотр журнала и текущего состояния Apache
  41. PID file /run/httpd/httpd.pid not readable (yet?) after start
  42. Обновление с Apache 2.2 до 2.4
  43. Apache is running a threaded MPM, but your PHP Module is not compiled to be threadsafe

Apache HTTP Server

The Apache HTTP Server, or Apache for short, is a very popular web server, developed by the Apache Software Foundation.

This article describes how to set up Apache and how to optionally integrate it with PHP.

Contents

Installation

Configuration

Apache configuration files are located in /etc/httpd/conf . The main configuration file is /etc/httpd/conf/httpd.conf , which includes various other configuration files. The default configuration file should be fine for a simple setup. By default, it will serve the directory /srv/http to anyone who visits your website.

To start Apache, start httpd.service using systemd.

Apache should now be running. Test by visiting http://localhost/ in a web browser. It should display a simple index page.

For optional further configuration, see the following sections.

Advanced options

These options in /etc/httpd/conf/httpd.conf might be interesting for you:

For security reasons, as soon as Apache is started by the root user (directly or via startup scripts) it switches to this UID. The default user is http, which is created automatically during installation. This is the port Apache will listen to. For Internet-access with router, you have to forward the port. If you want to setup Apache for local development you may want it to be only accessible from your computer. Then change this line to Listen 127.0.0.1:80 . This is the admin’s email address which can be found on e.g. error pages. This is the directory where you should put your web pages. Change it, if you want to, but do not forget to also change to whatever you changed your DocumentRoot to, or you will likely get a 403 Error (lack of privileges) when you try to access the new document root. Do not forget to change the Require all denied line to Require all granted , otherwise you will get a 403 Error. Remember that the DocumentRoot directory and its parent folders must allow execution permission to others (can be set with chmod o+x /path/to/DocumentRoot ), otherwise you will get a 403 Error. This directive in sections causes Apache to completely ignore .htaccess files. Note that this is now the default for Apache 2.4, so you need to explicitly allow overrides if you plan to use .htaccess files. If you intend to use mod_rewrite or other settings in .htaccess files, you can allow which directives declared in that file can override server configuration. For more info refer to the Apache documentation.

More settings can be found in /etc/httpd/conf/extra/httpd-default.conf :

To turn off your server’s signature:

To hide server information like Apache and PHP versions:

User directories

User directories are available by default through http://localhost/

yourusername/ and show the contents of

/public_html (this can be changed in /etc/httpd/conf/extra/httpd-userdir.conf ).

If you do not want user directories to be available on the web, comment out the following line in /etc/httpd/conf/httpd.conf :

The factual accuracy of this article or section is disputed.

You must make sure that your home directory permissions are set properly so that Apache can get there. Your home directory and

/public_html must be executable for others («rest of the world»):

Restart httpd.service to apply any changes. See also Umask#Set the mask value.

In /etc/httpd/conf/httpd.conf , uncomment the following three lines:

If using certbot —apache , the following line needs to be uncommented as well:

After obtaining a key and certificate, make sure the SSLCertificateFile and SSLCertificateKeyFile lines in /etc/httpd/conf/extra/httpd-ssl.conf point to the key and certificate. If a concatenated chain of CA certificates was also generated, add that filename against SSLCertificateChainFile .

Finally, restart httpd.service to apply any changes.

Virtual hosts

If you want to have more than one host, uncomment the following line in /etc/httpd/conf/httpd.conf :

Читайте также:  Memtest для mac os

In /etc/httpd/conf/extra/httpd-vhosts.conf set your virtual hosts. The default file contains an elaborate example that should help you get started.

To test the virtual hosts on your local machine, add the virtual names to your /etc/hosts file:

Restart httpd.service to apply any changes.

Managing many virtual hosts

If you have a huge amount of virtual hosts, you may want to easily disable and enable them. It is recommended to create one configuration file per virtual host and store them all in one folder, eg: /etc/httpd/conf/vhosts .

First create the folder:

Then place the single configuration files in it:

In the last step, Include the single configurations in your /etc/httpd/conf/httpd.conf :

You can enable and disable single virtual hosts by commenting or uncommenting them.

A very basic vhost file will look like this:

Extensions

First install PHP, then follow one of the next three subsections below. Finally, test the installation as described in the final subsection.

Using libphp

This method is probably the easiest, but is also the least scalable: it is suitable for a light request load. It also requires you to change the mpm module, which may cause problems with other extensions (e.g. it is not compatible with #HTTP/2).

Install php7-apache for PHP 7 or php-apache for PHP 8, as appropriate.

In /etc/httpd/conf/httpd.conf , comment the line:

and uncomment the line:

Otherwise you will get the following error:

As an alternative, you can use mod_proxy_fcgi (see #Using php-fpm and mod_proxy_fcgi below).

To enable PHP, add these lines to /etc/httpd/conf/httpd.conf :

  • Place this at the end of the LoadModule list:
  • Place this at the end of the Include list:

Using apache2-mpm-worker and mod_fcgid

This method provides improved performance and memory usage when serving multiple requests.

Create the needed directory and symlink it for the PHP wrapper:

Create /etc/httpd/conf/extra/php-fcgid.conf with the following content:

  • Uncomment the loading of the actions module:
  • Load the FCGID module after the loading of the unixd module (on which it is dependent) — you may wish to place this within the block:
  • Ensure that the inclusion of the MPM configuration is uncommented (it is uncommented in the default installed version of this file):
  • Add an inclusion of your new FCGID configuration:

Using php-fpm and mod_proxy_fcgi

This method provides «an alternative PHP FastCGI implementation with some additional features (mostly) useful for heavy-loaded sites» [1].

Enable proxy modules:

Create /etc/httpd/conf/extra/php-fpm.conf with the following content:

And include it at the bottom of /etc/httpd/conf/httpd.conf :

You can configure PHP-FPM in /etc/php/php-fpm.d/www.conf , but the default setup should work fine.

Start and enable php-fpm.service . Restart httpd.service .

Test whether PHP works

To test whether PHP was correctly configured, create a file called test.php in your Apache DocumentRoot directory (e.g. /srv/http/ or

/public_html/ ) with the following contents:

/test.php as appropriate.

HTTP/2

To enable HTTP/2 over TLS support, uncomment the following line in httpd.conf :

And add the following line:

To debug, you can set only the module rather than the entire server to debug or info :

For more information – including extra HTTP/2 feature settings – see the mod_http2 documentation.

Troubleshooting

Apache Status and Logs

See the status of the Apache daemon with systemctl.

Apache logs can be found in /var/log/httpd/

Error: PID file /run/httpd/httpd.pid not readable (yet?) after start

Comment out the unique_id_module line in httpd.conf : #LoadModule unique_id_module modules/mod_unique_id.so

/run/httpd not being created at boot

If systemd-tmpfiles —create as the root user complains about «unsafe path transition», check ownership of your root directory.

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

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

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 mpm_event_module with mpm_prefork_module :

and restart httpd.service .

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 httpd.conf that you might not have reproduced in your local configuration. To fix it, uncomment the following line.

and restart httpd.service .

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:

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.

Читайте также:  Pip install requirements txt windows

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:

AH01071: Got error ‘Primary script unknown’

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

Changing the max_execution_time in php.ini has no effect

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

and restart httpd.service .

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:

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

Источник

Apache HTTP Server (Русский)

Перевод этой статьи или раздела не отражает оригинальное содержание.

Apache HTTP Server, или сокращенно Apache — популярный веб-сервер, разработанный Apache Software Foundation.

Apache часто используется вместе с языком сценариев PHP и СУБД MySQL. Такую комбинацию обычно называют LAMP (Linux, Apache, MySQL, PHP). Эта статья объясняет, как настроить Apache и как интегрировать с ним PHP и MySQL.

Если вам нужно быстро создать окружение для разработки и тестирования, то можете просто установить Xampp.

Contents

Установка

Настройка

Файлы настроек Apache находятся в /etc/httpd/conf . Основным файлом является /etc/httpd/conf/httpd.conf , который может по ссылкам включать в себя дополнительные файлы с настройками. В большинстве случаев будет достаточно стандартных настроек из этого файла. По умолчанию корневым каталогом веб-сервера является /srv/http .

Для старта Apache запустите службу httpd.service .

После этих действий Apache должен запуститься. Проверьте работает ли он, набрав в адресной строке браузера http://localhost/ . Веб-сервер должен отправить вам простую тестовую страничку.

При необходимости дальнейшей настройки сервера смотрите следующие разделы.

Дополнительные опции

Следующие опции (директивы) в /etc/httpd/conf/httpd.conf могут быть вам интересны:

По соображениям безопасности при запуске сервера Apache от имени суперпользователя (напрямую или через скрипт инициализации) происходит смена идентификатора пользователя (UID), от имени которого выполняется процесс сервера. По умолчанию используется пользователь http , который не имеет привилегированных полномочий в системе. Это порт, через который Apache принимает входящие соединения. Если сервер имеет выход в интернет через маршрутизатор, необходимо будет настроить перенаправление этого порта. Если вы используете Apache для разработки и тестирования, вы можете разрешить только локальный доступ к нему. Для этого укажите Listen 127.0.0.1:80 . Адрес электронной почты администратора, который будет выводиться, например, на странице ошибки Apache. Это корневая директория Apache, в которой можно разместить ваши веб-страницы. Измените ее, если нужно, но не забудьте также поменять путь в директиве на новое расположение DocumentRoot , иначе вы, скорее всего, получите сообщение об ошибке 403 Error (недостаточно полномочий) при попытке получить доступ к новому корневому каталогу Apache. Также не забудьте изменить строку Require all denied на Require all granted , иначе снова получите ошибку 403 Error. Помните, что директория DocumentRoot и ее родительские папки должны иметь разрешения на запуск для всех (можно установить командой chmod o+x /path/to/DocumentRoot> ), в противном случае вы получите ошибку 403 Error. Запрещает переопределение настроек. Если в секции указана эта директива, Apache будет полностью игнорировать настройки в файле .htaccess . Обратите внимание, что теперь такая настройка для Apache 2.4 является настройкой по умолчанию, поэтому если вы планируете использовать .htaccess , вам необходимо дать соответствующие разрешения. Если вы собираетесь включить модуль mod_rewrite или использовать настройки в .htaccess , вы можете определить какие из директив, объявленных в этих файлах, могут перезаписывать конфигурацию сервера. Для получения дополнительной информации обратитесь к документации Apache.

Дополнительные настройки можно найти в /etc/httpd/conf/extra/httpd-default.conf .

Чтобы полностью отключить вывод версии Apache в генерируемых сервером страницах, добавьте:

Чтобы подавить вывод такой информации, как версии Apache и PHP, добавьте:

Пользовательские каталоги

По умолчанию доступ к каталогам пользователей возможен по адресу http://localhost/

»user»/ , который показывает содержимое каталога

/public_html (его имя и расположение задается в файле /etc/httpd/conf/extra/httpd-userdir.conf ).

Если вы не хотите, чтобы пользовательские каталоги были доступны через web, закомментируйте следующую строку в /etc/httpd/conf/httpd.conf :

Убедитесь, что права доступа к вашему домашнему каталогу и

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

Однако с точки зрения безопасности вышеприведенное решение слишком фривольно. Правильнее поступить по-другому. Сначала добавьте пользователя http в группу, которой принадлежит ваша домашняя папка. Например, если ваша домашняя папка и все ее подкаталоги принадлежат группе piter, можно проделать следующее:

Читайте также:  Комплект поставки windows 10

После этого назначьте права на чтение и исполнение для каталогов

/public_html и, рекурсивно, на остальные подкаталоги для

/public_html для членов группы (в нашем примере для членов группы piter). Опираясь на нижеприведенный шаблон, осуществите эти мероприятия:

Перезапустите службу httpd.service , чтобы изменения вступили в силу. Смотрите также Umask#Set the mask value.

TLS/SSL

Для использования TLS/SSL необходимо установить openssl .

Создайте закрытый ключ и запрос на получение сертификата (CSR). Также вы можете самозаверить CSR (который создаст сертификат):

Теперь раскомментируйте следующие строки в /etc/httpd/conf/httpd.conf :

Перезапустите службу httpd.service , чтобы изменения вступили в силу.

Виртуальные хосты

Если вы хотите, чтобы Apache обслуживал не один, а несколько хостов, раскомментируйте следующую строку в файле /etc/httpd/conf/httpd.conf :

Укажите свои виртуальные хосты в /etc/httpd/conf/extra/httpd-vhosts.conf . Файл уже содержит пример полностью рабочих настроек, что поможет вам быстро выполнить настройки под ваши нужды.

Для проверки виртуальных хостов на локальной машине добавьте их виртуальные имена в ваш файл /etc/hosts :

Перезапустите httpd.service , чтобы изменения вступили в силу.

Управление большим количеством виртуальных хостов

Если Apache используется для обслуживания очень большого количества виртуальных хостов, вам может быть полезна возможность их легко включать и отключать. Для этого рекомендуется создавать собственный файл настроек на каждый хост и хранить все эти файлы в одном каталоге, например /etc/httpd/conf/vhosts .

Сначала создайте каталог:

Теперь создайте в нем отдельные конфигурационные файлы:

И включите эти файлы в основной файл настроек /etc/httpd/conf/httpd.conf :

Теперь можно быстро включать/отключать требуемые виртуальные хосты, просто закомментировав или раскомментировав соответствующие директивы Include в основном файле настроек.

Очень простой файл виртуального хоста будет выглядеть следующим образом:

Расширения

Для использования mod_mpm_prefork , откройте /etc/httpd/conf/httpd.conf и поменяйте строку

Также вы можете просто использовать mod_proxy_fcgi (смотрите #Использование php7 c php-fpm и mod_proxy_fcgi [ссылка недействительна: раздел не найден] ).

Чтобы включить модуль PHP, добавьте следующие строки в /etc/httpd/conf/httpd.conf :

  • Поместите эту строку в любом месте после строки LoadModule dir_module modules/mod_dir.so :
  • Разместите эту строку в конце списка Include :

Если ваш корневой каталог DocumentRoot не /srv/http , добавьте его в список open_basedir в /etc/php/php.ini (необязательно):

Перезапустите службу httpd.service , чтобы изменения вступили в силу.

Чтобы убедиться в том, что PHP настроен корректно, создайте файл test.php в каталоге DocumentRoot (то есть в /srv/http/ или

/public_html ) и поместите в него следующий код:

По адресу http://localhost/test.php или http://localhost/»

пользователь»/test.php вы должны увидеть информационную страницу PHP.

Если PHP-код не исполняется, а на странице браузера вы увидите содержимое test.php , проверьте добавили ли вы Includes в строку Options для вашего корневого каталога в /etc/httpd/conf/httpd.conf . Кроме того, убедитесь, что TypesConfig conf/mime.types раскомментирован в секции . Также можно попробовать добавить нижеследующую строку в секцию файла httpd.conf :

Дополнительную информацию вы можете получить на странице PHP.

Дополнительные параметры

Рекомендуется правильно настроить вашу временную зону (список временных зон) в /etc/php/php.ini по примеру:

По желанию включите режим показа ошибок при отладке PHP-кода, для этого измените значение опции display_errors на On в файле /etc/php/php.ini :

Ежели вы хотите использовать модуль libGD , установите php-gd и раскомментируйте extension=gd.so в /etc/php/php.ini :

Для использования модуля mcrypt установите php-mcrypt AUR и раскомментируйте extension=mcrypt.so в /etc/php/php.ini :

Не забудьте добавить индексные файлы /etc/httpd/conf/extra/php7_module.conf , если это необходимо:

Для дополнительной настройки, пожалуйста прочтите PHP.

Использование php5 c php-fpm и mod_proxy_fcgi

  • Установитеphp-fpm
  • Задайте listen в /etc/php/php-fpm.conf следующим образом:
  • Добавьте следующие строки в /etc/httpd/conf/httpd.conf :
  • Если у вас добавлен модуль php, уберите его, так как он больше не нужен:
  • Перезапустите демон apache php-fpm:

Использование php5 c apache2-mpm-worker и mod_fcgid

  • Раскомментируйте следующую строку в /etc/conf.d/apache :
  • Раскомментируйте следующую строку в /etc/httpd/conf/httpd.conf :
  • Установите пакеты mod_fcgid и php-cgi , доступные в официальных репозиториях.
  • Создайте файл /etc/httpd/conf/extra/php5_fcgid.conf со следующим содержимым:
  • Создайте каталог и символическую ссылку в нем на php-cgi:
  • Отредактируйте /etc/httpd/conf/httpd.conf :

и перезапустите службу httpd.service .

MySQL/MariaDB

Следуйте инструкциям на странице PHP#MySQL/MariaDB.

После выполнения настройки, перезапустите службу mysqld , чтобы изменения вступили в силу.

Решение проблем

Просмотр журнала и текущего состояния Apache

Текущее состояние службы httpd вы можете вывести командой systemctl status httpd .

Лог-файлы Apache вы найдете в каталоге /var/log/httpd .

PID file /run/httpd/httpd.pid not readable (yet?) after start

Если вы получаете такую ошибку, закомментируйте строку:

в файле настроек Apache.

Обновление с Apache 2.2 до 2.4

Если вы используете php-apache , посмотрите инструкции к Apache с PHP выше.

Управление доступом было изменено. Приведите все директивы Order , Allow , Deny и Satisfy к новому синтаксису с Require . mod_access_compat позволит использовать устаревший формат на время этапа перехода.

Подробную информацию вы найдете на странице Upgrading to 2.4 from 2.2.

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

Если не удалось запустить php5_module при старте httpd.service и вы получаете следующее сообщение об ошибке:

Это значит, что Apache работает c поточным MPM, но используется не потокобезопасная версия PHP. В этом случае, следует заменить mpm_event_module на mpm_prefork_module :

Источник

Оцените статью