HTTPD - Apache2 интернет сервер Сравнение версий

Различия

Здесь показаны различия между двумя версиями данной страницы.

Ссылка на это сравнение

Предыдущая версия справа и слева Предыдущая версия
Следующая версия
Предыдущая версия
wiki:руководство_по_ubuntu_server:web_сервера:httpd_apache2_web_server [2012/06/26 21:40]
[HTTPD - Apache2 интернет сервер]
wiki:руководство_по_ubuntu_server:web_сервера:httpd_apache2_web_server [2014/07/24 15:25] (текущий)
[Настройка]
Строка 1: Строка 1:
 <style float-left>​ <style float-left>​
 [[wiki:​руководство_по_ubuntu_server|Руководство по Ubuntu Server]] >> [[wiki:​руководство_по_ubuntu_server|Руководство по Ubuntu Server]] >>
-[[wiki:​руководство_по_ubuntu_server:​web_сервера|Мониторинг]]</​style>​+[[wiki:​руководство_по_ubuntu_server:​web_сервера|Интернет сервера]]</​style>​
 <style float-right>​ <style float-right>​
 [[wiki:​руководство_по_ubuntu_server:​web_сервера|<​-назад]] |  [[wiki:​руководство_по_ubuntu_server:​web_сервера|<​-назад]] | 
 [[wiki:​руководство_по_ubuntu_server:​web_сервера:​php5_script_language|далее->​]]</​style>​ [[wiki:​руководство_по_ubuntu_server:​web_сервера:​php5_script_language|далее->​]]</​style>​
- 
  
 =====HTTPD - Apache2 интернет сервер===== =====HTTPD - Apache2 интернет сервер=====
Строка 23: Строка 22:
 ====Установка==== ====Установка====
  
-The Apache2 ​web server is available in Ubuntu Linux. ​To install ​Apache2:+Интернет-сервер ​Apache2 ​доступен в Ubuntu Linux. ​Для установки ​Apache2:
  
-    At a terminal prompt enter the following command+  -- В терминале введите следующую команду
- +<​code>​sudo apt-get install apache2</​code>​
-    ​sudo apt-get install apache2+
  
 ====Настройка==== ====Настройка====
  
-Apache2 ​is configured by placing ​directives ​in plain text configuration filesThese directives are separated between the following files and directories:+Apache2 ​настраивается помещением **инструкций** (directives) в обычные тестовые файлы настроекЭти инструкции разделены между следующими файлами и каталогами: 
 +  -- **apache2.conf**:​ основной файл настроек Apache2. Содержит **глобальные** настройки для всего Apache2. 
 +  -- **conf.d**: (каталог) содержит файлы настроек,​ которые применяются **глобально** к Apache2. Другие пакеты,​ которые используют Apache2 для предоставления контента,​ могут добавлять файлы или символьные ссылки в этот каталог. 
 +  -- **envvars**:​ файл, где устанавливаются **переменные окружения** Apache2. 
 +  -- **httpd.conf**:​ устаревший основной файл настроек Apache2, названный по имени сервиса **httpd**. Теперь этот файл обычно пустой,​ поскольку большинство опций настроек были перемещены в каталоги,​ упомянутые далее. Файл может быть использован для для специфичных настроек пользователя,​ имеющих глобальный эффект в Apache2. 
 +  -- **mods-available**:​ этот каталог содержит конфигурационные файлы как для загрузки модулей,​ так и для их настройки. Тем не менее не все модули имеют отдельные файлы настройки. 
 +  -- **mods-enabled**:​ содержит **символьные ссылки** на файлы в /​etc/​apache2/​mods-available. Когда создается символьная ссылка на файл настроек модуля,​ он включается при следующем рестарте **apache2**. 
 +  -- **ports.conf**:​ содержит инструкции,​ которые определяют какие TCP порты прослушивает Apache2. 
 +  -- **sites-available**:​ этот каталог содержит файлы настроек для **виртуальных сетевых узлов** (Virtual Hosts) Apache2. Виртуальные сетевые узлы позволяют настраивать Apache2 на множество сайтов с отдельными конфигурациями. 
 +  -- **sites-enabled**:​ подобно mods-enabled содержит символьные ссылки на каталог /​etc/​apache2/​sites-available. Аналогично,​ когда файл настроек из sites-available получает здесь символьную ссылку,​ соответствующий ему сайт будет активен при следующем перезапуске Apache2.
  
-    apache2.conf: the main Apache2 configuration fileContains settings that are global to Apache2.+В дополнение к этому другие файлы настроек могут быть добавлены с использованием инструкции **Include**,​ а символы группировок могут использоваться для включения множества файлов настроекЛюбая инструкция может быть добавлена в любой из этих файлов настроекИзменения в основных конфигурационных файлах распознаются только после старта или рестарта ​Apache2.
  
-    conf.d: contains configuration files which apply globally to Apache2. Other packages that use Apache2 to serve content may add filesor symlinks, to this directory. +Сервер также читает файлысодержащие типы ​mime документовимя файла задается инструкцией **TypesConfig**обычно через ​/​etc/​apache2/​mods-available/​mime.conf, ​который также может включать дополнения и переопределенияа по умолчанию используется ​/​etc/​mime.types.
- +
-    envvars: file where Apache2 environment variables are set. +
- +
-    httpd.conf: historically the main Apache2 configuration file, named after the httpd daemon. Now the file is typically empty, as most configuration options have been moved to the below referenced directories. The file can be used for user specific configuration options that globally effect Apache2. +
- +
-    mods-available:​ this directory contains configuration files to both load modules and configure them. Not all modules will have specific configuration files, however. +
- +
-    mods-enabled:​ holds symlinks to the files in /​etc/​apache2/​mods-available. When a module configuration file is symlinked it will be enabled the next time apache2 is restarted. +
- +
-    ports.conf: houses the directives that determine which TCP ports Apache2 is listening on. +
- +
-    sites-available:​ this directory has configuration files for Apache2 Virtual Hosts. Virtual Hosts allow Apache2 to be configured for multiple sites that have separate configurations. +
- +
-    sites-enabled:​ like mods-enabled,​ sites-enabled contains symlinks to the /​etc/​apache2/​sites-available directory. Similarly when a configuration file in sites-available is symlinked, the site configured by it will be active once Apache2 is restarted. +
- +
-In addition, other configuration files may be added using the Include directive, and wildcards can be used to include many configuration files. Any directive may be placed in any of these configuration files. Changes to the main configuration files are only recognized by Apache2 when it is started or restarted. +
- +
-The server also reads a file containing ​mime document typesthe filename is set by the TypesConfig ​directivetypically via /​etc/​apache2/​mods-available/​mime.conf, ​which might also include additions and overridesand is /​etc/​mime.types ​by default.+
  
 ===Общие настройки=== ===Общие настройки===
  
-This section explains ​Apache2 ​server essential configuration parametersRefer to the Apache2 ​Documentation for more details.+Этот раздел рассматривает существенные параметры настройки сервера ​Apache2. ​Обратитесь к [[http://​httpd.apache.org/​docs/​2.2/​|документации по Apache2]] для уточнения деталей.
  
-    ​Apache2 ​ships with a virtual-host-friendly default configurationThat isit is configured with a single default virtual host (using the VirtualHost ​directivewhich can modified or used as-is if you have a single siteor used as a template for additional virtual hosts if you have multiple sitesIf left alonethe default virtual host will serve as your default siteor the site users will see if the URL they enter does not match the ServerName ​directive of any of your custom sitesTo modify the default virtual host, edit the file /​etc/​apache2/​sites-available/​default.+ ​1. ​Apache2 ​по умолчанию поставляется с конфигурацией,​ дружественной к виртуальным хостамЭто означаетчто он изначально настроен с единственным виртуальным хостом ​(используя инструкцию ​VirtualHost) ​который может быть изменен или использоваться как естьесли у вас единственный сайт, либо использоваться как шаблон для дополнительных виртуальных хостов,​ если у вас несколько сайтовЕсли оставить его единственнымизначальный виртуальный хост будет обслуживать ваш сайт по умолчанию или пользователи сайта заметятчто введенный ими ​URL не совпадает с инструкцией **ServerName** любого из ваших созданных сайтовДля изменения начального виртуального хоста отредактируйте файл ​/​etc/​apache2/​sites-available/​default.
  
-    The directives set for a virtual host only apply to that particular virtual hostIf a directive is set server-wide and not defined within the virtual host settingsthe default setting is usedFor exampleyou can define a Webmaster ​email address and not define individual email addresses for each virtual host.+<​note>​Инструкции,​ установленные для виртуального хоста, влияют только на соответствующий виртуальный хостЕсли инструкция установлена на весь сервер и не установлена в настройках виртуального хостаиспользуется общая настройкаНапримервы можете определить ​email адрес вебмастера и не определять его отдельно для каждого виртуального хоста.</​note>​ 
 +Если вы хотите настроить новый виртуальный хост или сайт, скопируйте этот файл в тот же каталог с новым именем. Например:​ 
 +<​code>​sudo cp /​etc/​apache2/​sites-available/​default /​etc/​apache2/​sites-available/​mynewsite</​code>​ 
 +Отредактируйте новый файл для настройки нового сайта, используя инструкции,​ описанные ниже.
  
-    If you wish to configure a new virtual host or sitecopy that file into the same directory with a name you chooseFor example:+ 2. Инструкция **ServerAdmin** определяет адрес email для оповещения администратора сервера. Изначальное значение webmaster@localhost. Его надо изменить на ваш email адрес (если именно вы являетесь администратором сервера). Если возникает проблема с сайтомApache2 показывает сообщение об ошибке,​ содержащее этот адрес для оповещения о проблеме. Ищите эту инструкцию в файле настроек вашего сайта в каталоге /​etc/​apache2/​sites-available.
  
-    sudo cp /​etc/​apache2/​sites-available/​default /​etc/​apache2/​sites-available/​mynewsite+ 3. Инструкция **Listen** определяет порт, и в общем случае IP адрес, на которых Apache2 должен ожидать соединения. Если IP адрес не определен,​ Apache2 будет прослушивать все IP адреса,​ которые назначены компьютеру,​ где он запущен. Значение по умолчанию для **Listen** 80. Замените его на 127.0.0.1:​80 чтобы Apache2 прослушивал только интерфейс внутренней петли, что сделает его недоступным из интернета;​ на 81 (например) для изменения порта доступа или оставьте как есть для стандартного функционирования. Эта инструкция может быть найдена и изменена в единственном файле ​/​etc/​apache2/​ports.conf.
  
-    Edit the new file to configure the new site using some of the directives described below.+ 4. Инструкция **ServerName** необязательная и определяет на какой адрес FQDN ваш сайт должен отвечать. Изначальный виртуальный хост не имеет ServerName, поэтому отвечает на все запросы не соответствующие директивам ServerName других виртуальных хостов. Если вы приобрели доменное имя ubunturocks.com и хотите прописать его на вашем Ubuntu сервере,​ значение ServerName для файла настроек вашего виртуального хоста должно быть ubunturocks.com. Добавьте эту инструкцию в файл нового виртуального хоста, который вы создавали ранее (/​etc/​apache2/​sites-available/​mynewsite).
  
-    The ServerAdmin directive specifies the email address to be advertised for the server'​s administratorThe default value is webmaster@localhostThis should be changed to an email address that is delivered to you (if you are the server'​s administrator). If your website has a problemApache2 will display an error message containing this email address to report the problem toFind this directive in your site's configuration file in /​etc/​apache2/​sites-available.+Возможно вы захотите,​ чтобы ваш сайт откликался на www.ubunturocks.comпоскольку многие пользователи считают префикс www необходимым. Используйте для этого инструкцию **ServerAlias**Вы можете также применять для ServerAlias групповые символы.
  
-    The Listen directive specifies the portand optionally the IP addressApache2 should listen onIf the IP address is not specified, Apache2 will listen on all IP addresses assigned to the machine it runs onThe default value for the Listen directive is 80Change this to 127.0.0.1:80 to cause Apache2 to listen only on your loopback interface so that it will not be available to the Internet, to (for example) 81 to change the port that it listens on, or leave it as is for normal operation. This directive can be found and changed in its own file, /etc/​apache2/​ports.conf+Напримерследующая конфигурация заставит ваш сайт отвечать на любые запросы с доменомоканчивающимся на .ubunturocks.com. 
 +<​code>​ServerAlias *.ubunturocks.com</code>
  
-    The ServerName directive is optional and specifies what FQDN your site should answer toThe default virtual host has no ServerName directive specified, so it will respond to all requests that do not match a ServerName directive in another virtual host. If you have just acquired the domain name ubunturocks.com and wish to host it on your Ubuntu server, the value of the ServerName directive in your virtual host configuration file should be ubunturocks.com. Add this directive to the new virtual host file you created earlier (/​etc/​apache2/​sites-available/​mynewsite). + 5Инструкция **DocumentRoot** определяет где ​Apache2 ​будет искать файлы, которые являются содержимым сайтаПо умолчанию используется значение ​/​var/​www, ​как определено в /​etc/​apache2/​sites-available/​default. ​Если желаетеможете изменить это значение в файле сайта вашего виртуального хоста и не забудьте создать этот каталогесли необходимо!
- +
-    You may also want your site to respond to www.ubunturocks.com,​ since many users will assume the www prefix is appropriate. Use the ServerAlias directive for this. You may also use wildcards in the ServerAlias directive. +
- +
-    For example, the following configuration will cause your site to respond to any domain request ending in .ubunturocks.com. +
- +
-    ServerAlias ​*.ubunturocks.com +
- +
-    The DocumentRoot ​directive specifies where Apache2 ​should look for the files that make up the siteThe default value is /​var/​www, ​as specified in /​etc/​apache2/​sites-available/​default. ​If desiredchange this value in your site's virtual host fileand remember to create that directory if necessary! +
- +
-Enable the new VirtualHost using the a2ensite utility and restart Apache2:+
  
 +Включите новый VirtualHost,​ используя утилиту **a2ensite**,​ и перезапустите Apache2:
 +<​code>​
 sudo a2ensite mynewsite sudo a2ensite mynewsite
 sudo service apache2 restart sudo service apache2 restart
- +</​code>​ 
-Be sure to replace ​mynewsite ​with a more descriptive name for the VirtualHost. ​One method is to name the file after the ServerName ​directive of the VirtualHost+<​note>​Убедитесь,​ что заменили **mynewsite** на более понятное имя для ​VirtualHost. ​Один из способов это называть файл по значению ​ServerName ​виртуального хоста.</​note>​ 
- +Аналогично используйте утилиту **a2dissite** для выключения сайтовЭто может быть полезным при разрешении проблем с несколькими виртуальными хостами
-Similarly, use the a2dissite ​utility to disable sitesThis is can be useful when troubleshooting configuration problems with multiple VirtualHosts+<​code>​
 sudo a2dissite mynewsite sudo a2dissite mynewsite
 sudo service apache2 restart sudo service apache2 restart
 +</​code>​
  
 ===Настройки по умолчанию=== ===Настройки по умолчанию===
  
-This section explains configuration of the Apache2 ​server default settingsFor exampleif you add a virtual hostthe settings you configure for the virtual host take precedence for that virtual hostFor a directive not defined within the virtual host settingsthe default value is used.+Этот раздел раскрывает возможности настроек значений по умолчанию сервера ​Apache2. ​Напримересли вы добавили виртуальный хостзначения,​ которые вы определите в его конфигурации переопределят значения для данного виртуального хостаДля инструкций,​ не определенных в настройках виртуального хостабудут использоваться значения по умолчанию.
  
-    The DirectoryIndex ​is the default page served by the server when a user requests an index of a directory by specifying a forward slash (/) at the end of the directory name.+ 1. **DirectoryIndex** - это страница по умолчанию,​ выдаваемая сервером,​ когда пользователь запрашивает индекс каталога указанием прямого слеша ​(/) после его имени.
  
-    For examplewhen a user requests the page http://​www.example.com/​this_directory/, ​he or she will get either the DirectoryIndex ​page if it existsa server-generated directory list if it does not and the Indexes ​option is specifiedor a Permission Denied ​page if neither is trueThe server will try to find one of the files listed in the DirectoryIndex ​directive and will return the first one it findsIf it does not find any of these files and if Options Indexes ​is set for that directorythe server will generate and return a list, in HTML format, of the subdirectories and files in the directoryThe default valuefound in /​etc/​apache2/​mods-available/​dir.conf ​is "​index.html index.cgi index.pl index.php index.xhtml index.htm"​. ​Thusif Apache2 ​finds a file in a requested directory matching any of these namesthe first will be displayed.+Напримеркогда пользователь запрашивает страницу ​http://​www.example.com/​this_directory/, ​он (или она) получит либо страницу,​ определяемую **DirectoryIndex**если она существует,​ список файлов в каталоге,​ сгенерированный сервером,​ если не существует и определена опция **Indexes**или страницу ​Permission Denied ​(недостаточно прав доступа) в остальных случаяхСервер попытается найти один из файлов,​ перечисленных в инструкции **DirectoryIndex** и вернет первый найденныйЕсли не найдет ни одного и если установлено ​Options Indexes ​для данного каталогасервер создаст и вернет список в формате ​HTML подкаталогов и файлов в этом каталогеЗначение по умолчаниюнаходящееся в /​etc/​apache2/​mods-available/​dir.conf ​это ​"​index.html index.cgi index.pl index.php index.xhtml index.htm"​. ​Поэтомуесли ​Apache2 ​найдет файл в запрашиваемом каталоге,​ соответствующий любому из этих именпервый же из них будет показан [клиенту].
  
-    The ErrorDocument ​directive allows you to specify a file for Apache2 ​to use for specific error eventsFor exampleif a user requests a resource that does not exist404 error will occurBy default, ​Apache2 ​will simply return a HTTP 404 Return codeRead /​etc/​apache2/​conf.d/​localized-error-pages ​for detailed instructions for using ErrorDocument, ​including locations of example files.+ 2. Инструкция **ErrorDocument** позволяет вам определить файл для ​Apache2, используемый при определенных ошибочных событияхНапримересли пользователь запросил ресурскоторый не существует,​ возникнет ошибка ​404. По умолчанию ​Apache2 ​просто вернет код возврата ​HTTP 404. Прочитайте ​/​etc/​apache2/​conf.d/​localized-error-pages ​для детальных инструкций по использованию ​ErrorDocument, ​включающий расположение файлов примеров.
  
-    By default, the server writes the transfer log to the file /​var/​log/​apache2/​access.log. ​You can change this on a per-site basis in your virtual host configuration files with the CustomLog ​directiveor omit it to accept the default, specified in /​etc/​apache2/​conf.d/​other-vhosts-access-log. ​You may also specify the file to which errors are loggedvia the ErrorLog ​directivewhose default is /var/​log/​apache2/​error.log. ​These are kept separate from the transfer logs to aid in troubleshooting problems with your Apache2 ​serverYou may also specify the LogLevel (the default value is "​warn"​) ​and the LogFormat (see /​etc/​apache2/​apache2.conf ​for the default value).+ 3. По умолчанию сервер пишет журнал обмена в файл ​/​var/​log/​apache2/​access.log. ​Вы можете поменять это для каждого сайта в файлах настроек ваших виртуальных хостов с помощью инструкции **CustomLog** или спуститься на уровень настроек по умолчаниюопределяемых в /​etc/​apache2/​conf.d/​other-vhosts-access-log. ​Вы можете также определить файлв который будут сохраняться ошибки,​ через инструкцию **ErrorLog**которая изначально указывает на var/​log/​apache2/​error.log. ​Они хранятся отдельно от журнала обмена чтобы помочь в решении проблем с вашим сервером ​Apache2. ​Вы можете также определить **LogLevel** (изначально значение %%"​warn"​%%и **LogFormat** (смотрите ​/​etc/​apache2/​apache2.conf ​для значений по умолчанию).
  
-    Some options are specified on a per-directory basis rather than per-server. Options ​is one of these directivesDirectory ​stanza is enclosed in XML-like tagslike so:+ 4Некоторые опции задаются на уровне каталогов вместо уровня сервера. **Options** - одна из таких директивРаздел **Directory** заключается в XML-подобные теги, как показано ниже:  
 +<​code>​ 
 +<​Directory /​var/​www/​mynewsite>​ 
 +... 
 +</​Directory>​ 
 +</​code>​ 
 +Инструкция **Options** внутри раздела **Directory** принимает одно или несколько из следующих значений (среди прочего)разделенные пробелами:
  
-    <​Directory /​var/​www/​mynewsite>​ +  ** **ExecCGI** Разрешает выполнение ​CGI сценариев. CGI сценарии не выполняются,​ если данная опция не выбрана
-    ... +<note tip>​Большинство файлов не должны выполняться как ​CGI сценарииЭто может быть очень опасно. CGI сценарии должны находиться в отдельном каталоге и вне вашего **DocumentRoot**. И только для этого каталога должна указываться опция **ExecCGI**Так сделано изначально и по умолчанию ​CGI сценарии располагаются в /​usr/​lib/​cgi-bin.</​note>​ 
-    </​Directory>​ +  ** **Includes** Позволяет включения на стороне сервераВключения на стороне сервера позволяют файлам ​HTML включать другие файлы. Смотрите [[https://​help.ubuntu.com/​community/​ServerSideIncludes|документацию ​Apache SSI (сообщества ​Ubuntu)]] для дополнительных деталей
- +  ** **IncludesNOEXEC** Позволяет включения на стороне серверано блокирует команды **#exec** и **#include** в CGI сценариях
-    The Options directive within a Directory stanza accepts one or more of the following values (among others), separated by spaces: +  ** **Indexes** Показывает форматированный список содержимого каталогаесли не найдены ​DirectoryIndex (как например ​index.html) ​в запрашиваемом каталоге
- +<note important>​По соображениям безопасности эта опция обычно не устанавливается и обычно не должна присутствовать для вашего каталога ​DocumentRoot. ​Включайте эту опцию осторожно на уровне каталогов только если вы уверены,​ что хотите показать пользователям полное содержание этого каталога.</​note>​ 
-        ​ExecCGI - Allow execution of CGI scripts. CGI scripts are not executed if this option is not chosen+  ** **Multiview** Поддерживает зависящие от содержимого просмотрыэта опция по умолчанию выключена по соображениям безопасностиСмотрите [[http://​httpd.apache.org/​docs/​2.2/​mod/​mod_negotiation.html#​multiviews|документацию ​Apache2 ​по этой опции]]
- +  ** **SymLinksIfOwnerMatch** Следует по символическим ссылкам если целевой файл или каталог имеет того же владельца,​ что и ссылка.
-        Most files should not be executed as CGI scriptsThis would be very dangerous. CGI scripts should kept in a directory separate from and outside your DocumentRoot, and only this directory should have the ExecCGI ​option setThis is the default, and the default location for CGI scripts is /​usr/​lib/​cgi-bin. +
- +
-        ​Includes - Allow server-side includesServer-side includes allow an HTML file to include other filesSee Apache SSI documentation ​(Ubuntu ​communityfor more information+
- +
-        ​IncludesNOEXEC - Allow server-side includesbut disable the #exec and #​include ​commands in CGI scripts+
- +
-        ​Indexes - Display a formatted list of the directory'​s contentsif no DirectoryIndex (such as index.html) ​exists in the requested directory+
- +
-        For security reasons, this should usually not be set, and certainly should not be set on your DocumentRoot ​directoryEnable this option carefully on a per-directory basis only if you are certain you want users to see the entire contents of the directory+
- +
-        ​Multiview - Support content-negotiated multiviewsthis option is disabled by default for security reasonsSee the Apache2 ​documentation on this option+
- +
-        ​SymLinksIfOwnerMatch - Only follow symbolic links if the target file or directory has the same owner as the link.+
  
 ===Настройки httpd=== ===Настройки httpd===
  
-This section explains some basic httpd daemon configuration settings.+Этот раздел раскрывает некоторые основные конфигурационные настройки сервиса **httpd**.
  
-LockFile - The LockFile ​directive sets the path to the lockfile ​used when the server is compiled with either ​USE_FCNTL_SERIALIZED_ACCEPT ​or USE_FLOCK_SERIALIZED_ACCEPT. ​It must be stored on the local diskIt should be left to the default value unless the logs directory is located on an NFS shareIf this is the case, the default value should be changed to a location on the local disk and to a directory that is readable only by root.+**LockFile** инструкция ​LockFile ​устанавливает путь к блокирующему файлу (lockfile) когда сервер скомпилирован с опцией ​USE_FCNTL_SERIALIZED_ACCEPT ​или ​USE_FLOCK_SERIALIZED_ACCEPT. ​Он должен сохраняться на локальном дискеСтоит оставить значение по умолчанию если только каталог журналов не расположен на NFS ресурсеВ противном случае исходное значение стоить изменить на каталог локального диска с правами на чтение только для ​root.
  
-PidFile - The PidFile ​directive sets the file in which the server records its process ​ID (pid). ​This file should only be readable by root. In most cases, it should be left to the default value.+**PidFile** инструкция ​PidFile ​устанавливает файл, в который сервер записывает ​ID своего процесса ​(pid). ​Этот файл должен быть доступен на чтение только ​root. В большинстве случаев этот параметр стоит оставить без изменений.
  
-User - The User directive sets the userid ​used by the server to answer requestsThis setting determines the server'​s accessAny files inaccessible to this user will also be inaccessible to your website'​s visitorsThe default value for User is "​www-data"​.+**User** инструкция ​User устанавливает ​userid ​(ID пользователя),​ используемый сервером для ответа на запросыЭта настройка определяет права доступа сервераЛюбые файлы, недоступные этому пользователю,​ также будут недоступны для посетителей вашего сайтаПо умолчанию используется пользователь ​"​www-data"​. 
 +<note important>​Пока вы находитесь в здравом уме и твердой памяти,​ не используйте в качестве пользователя root. Использование здесь root создаст серьезные пробоины в безопасности вашего сервера.</​note>​
  
-Unless you know exactly what you are doing, do not set the User directive to root. Using root as the User will create large security holes for your Web server. +**Group** инструкция ​Group аналогична директиве ​User. Group устанавливает группу под которой сервер будет отвечать на запросыЗначение по умолчанию также ​"​www-data"​.
- +
-Group - The Group directive is similar to the User directive. Group sets the group under which the server will answer requestsThe default group is also "​www-data"​.+
  
 ===Модули Apache2=== ===Модули Apache2===
  
-Apache2 ​is a modular serverThis implies that only the most basic functionality is included in the core serverExtended features are available through modules which can be loaded into Apache2. ​By default, a base set of modules is included in the server at compile-timeIf the server is compiled to use dynamically loaded modulesthen modules can be compiled separately, and added at any time using the LoadModule ​directiveOtherwise, ​Apache2 ​must be recompiled to add or remove modules.+Apache2 ​- модульный серверЭто означает,​ что только самая базовая функциональность включена в ядро сервераРасширенные возможности доступны через модули,​ которые могут быть загружены в Apache2. ​По умолчанию базовый набор модулей включается в сервер на этапе компиляцииЕсли сервер скомпилирован для использования динамически загружаемых модулейто модули могут быть скомпилированы отдельно и добавлены в любое время с использованием инструкции **LoadModule**В противном случае ​Apache2 ​должен быть перекомпилирован для добавления или удаления модулей.
  
-Ubuntu ​compiles ​Apache2 ​to allow the dynamic loading of modulesConfiguration directives may be conditionally included on the presence of a particular module by enclosing them in an <​IfModule> ​block.+Ubuntu ​компилирует ​Apache2 ​с возможностью динамической загрузки модулейКонфигурационные директивы могут быть включены по условию присутствия соответствующего модуля в блоке **<​IfModule>​**.
  
-You can install additional ​Apache2 ​modules and use them with your Web serverFor examplerun the following command from a terminal prompt to install the MySQL Authentication module:+Вы можете установить дополнительные модули ​Apache2 ​и использовать их с вашим интернет серверомНапримерзапустите следующую команду в терминале для установки модуля авторизации ​MySQL: 
 +<​code>​sudo apt-get install libapache2-mod-auth-mysql</​code>​
  
-sudo apt-get install libapache2-mod-auth-mysql +Ищите дополнительные модули в каталоге ​/​etc/​apache2/​mods-available.
- +
-See the /​etc/​apache2/​mods-available ​directory, for additional modules. +
- +
-Use the a2enmod utility to enable a module:+
  
 +Используйте утилиту a2enmod для включения модуля:​
 +<​code>​
 sudo a2enmod auth_mysql sudo a2enmod auth_mysql
 sudo service apache2 restart sudo service apache2 restart
- +</​code>​ 
-Similarly, ​a2dismod ​will disable a module+Аналогично ​a2dismod ​выключит модуль
 +<​code>​
 sudo a2dismod auth_mysql sudo a2dismod auth_mysql
 sudo service apache2 restart sudo service apache2 restart
 +</​code>​
  
 ====Настройка HTTPS==== ====Настройка HTTPS====
  
-The mod_ssl ​module adds an important feature to the Apache2 ​server ​the ability to encrypt communicationsThuswhen your browser is communicating using SSL, the https:// ​prefix is used at the beginning of the Uniform Resource Locator (URL) in the browser navigation bar.+Модуль **mod_ssl** добавляет важную возможность для сервера ​Apache2 - возможность шифрованных соединенийТаким образомкогда ваш браузер соединяется с использованием ​SSL, используется префикс %%https://%% в начале адреса ​URL в строке навигации.
  
-The mod_ssl ​module is available in apache2-common ​packageExecute the following command from a terminal prompt to enable the mod_ssl module:+Модуль **mod_ssl** доступен в пакете ​apache2-common. ​Выполните следующую команду в терминале для включения этого модуля: 
 +<​code>​sudo a2enmod ssl</​code>​
  
-sudo a2enmod ​ssl+Настройки по умолчанию для HTTPS находятся в файле /​etc/​apache2/​sites-available/​default-ssl. Чтобы Apache2 предоставлял HTTPS, также требуются файлы ключа и сертификата. Изначальная настройка HTTPS использует сертификат и ключ, созданные пакетом ssl-cert. Они подходят для тестирования,​ но должны быть заменены на сертификат,​ соответствующий вашему сайту или серверу. Для информации по созданию ключей и получению сертификатов смотрите раздел [[wiki:​руководство_по_ubuntu_server:​безопасность:​certificates|Сертификаты]].
  
-There is a default ​HTTPS configuration file in /etc/apache2/sites-available/default-ssl. In order for Apache2 to provide HTTPSa certificate and key file are also neededThe default HTTPS configuration will use a certificate and key generated by the ssl-cert package. They are good for testing, but the auto-generated certificate and key should be replaced by a certificate specific to the site or server. For information on generating a key and obtaining a certificate see Certificates+Для настройки Apache2 для HTTPS введите следующее:​ 
 +<​code>​sudo a2ensite ​default-ssl</​code>​ 
 +<​note>​Каталоги ​/etc/ssl/certs и /etc/ssl/private используются по умолчаниюЕсли вы установили сертификат и ключ в другие каталогиубедитесь что изменили соответственно опции SSLCertificateFile и SSLCertificateKeyFile.</​note>​
  
-To configure ​Apache2 ​for HTTPS, ​enter the following:+С Apache2, теперь настроенным на HTTPS, ​перезапустим сервис для разрешения новых настроек: 
 +<​code>​sudo service apache2 restart</​code>​ 
 +<​note>​В зависимости от того как вы выпускали свой сертификат,​ вам может потребоваться ввести кодовую фразу при старте Apache2.</​note>​
  
-sudo a2ensite default-ssl +Вы можете получить доступ к страницам защищенного сервера набрав %%https://​your_hostname/​url/​%% в адресной строке вашего браузера.
- +
-The directories /​etc/​ssl/​certs and /​etc/​ssl/​private are the default locations. If you install the certificate and key in another directory make sure to change SSLCertificateFile and SSLCertificateKeyFile appropriately. +
- +
-With Apache2 now configured for HTTPS, restart the service to enable the new settings: +
- +
-sudo service apache2 restart +
- +
-Depending on how you obtained your certificate you may need to enter a passphrase when Apache2 starts. +
- +
-You can access the secure server pages by typing ​https://​your_hostname/​url/ ​in your browser address bar.+
  
 ====Права разделения записи==== ====Права разделения записи====
  
-For more than one user to be able to write to the same directory it will be necessary to grant write permission to a group they share in commonThe following example grants shared write permission to /​var/​www ​to the group "​webmasters"​. +Чтобы более одного пользователя имели право записи в один и тот же каталог,​ необходимо дать право записи группе,​ которая их объединяетСледующий пример предоставляет права на запись в каталог ​/​var/​www ​для группы ​"​webmasters"​. 
 +<​code>​
 sudo chgrp -R webmasters /var/www sudo chgrp -R webmasters /var/www
 sudo find /var/www -type d -exec chmod g=rwxs "​{}"​ \; sudo find /var/www -type d -exec chmod g=rwxs "​{}"​ \;
 sudo find /var/www -type f -exec chmod g=rws  "​{}"​ \; sudo find /var/www -type f -exec chmod g=rws  "​{}"​ \;
- +</​code>​ 
-If access must be granted to more than one group per directoryenable Access Control Lists (ACLs).+<​note>​Если доступ должен быть предоставлен более чем одной группе на каталогиспользуйте Списки управляемого доступа ​(ACL).</​note>​
  
 ====Ссылки==== ====Ссылки====
  
-    Apache2 Documentation contains in depth information on Apache2 ​configuration directivesAlso, see the apache2-doc ​package for the official ​Apache2 ​docs+  -- [[http://​httpd.apache.org/​docs/​2.2/​|Документация по Apache2]] содержит более глубокую информацию по директивам настройкиТакже смотрите пакет **apache2-doc** для официальной документации по Apache2. 
- +  -- Смотрите сайт [[http://​www.modssl.org/​docs/​|документации по Mod SSL]] для дополнительной информации по SSL. 
-    See the Mod SSL Documentation site for more SSL related information+  -- [[http://​oreilly.com/​catalog/​9780596001919/​|Apache Cookbook]] от O'​Reilly ​- отличный ресурс по созданию специфичных настроек для ​Apache2. 
- +  -- Для вопросов по Apache2 ​в Ubuntu используйте IRC канал ​#​ubuntu-server ​на [[http://freenode.net/​|freenode.net]]
-    ​O'​Reilly's Apache Cookbook is a good resource for accomplishing specific ​Apache2 ​configurations+  -- Для обычно интегрируемого с PHP и MySQL Apache2 хорошим ресурсом будет страница[[https://​help.ubuntu.com/​community/​ApacheMySQLPHP|Apache MySQL PHP Ubuntu Wiki]].
- +
-    For Ubuntu specific ​Apache2 ​questions, ask in the #​ubuntu-server ​IRC channel on freenode.net. +
- +
-    Usually integrated with PHP and MySQL the Apache MySQL PHP Ubuntu Wiki page is a good resource. +
  
 ---- ----