Что такое apache? подробный обзор веб-сервера apache
Содержание:
Настройка Apache
Уже прошло то время, когда конфигурация Apache хранилась в одном файле. Но оно и правильно, когда все распределено по своим директориям, в конфигурационных файлах легче ориентироваться.
Все настройки содержатся в папке /etc/apache/:
- Файл /etc/apache2/apache2.conf отвечает за основные настройки
- /etc/apache2/conf-available/* — дополнительные настройки веб-сервера
- /etc/apache2/mods-available/* — настройки модулей
- /etc/apache2/sites-available/* — настойки виртуальных хостов
- /etc/apache2/ports.conf — порты, на которых работает apache
- /etc/apache2/envvars
Как вы заметили есть две папки для conf, mods и site. Это available и enabled. При включении модуля или хоста создается символическая ссылка из папки available (доступно) в папку enable (включено). Поэтому настройки лучше выполнять именно в папках available. Вообще говоря, можно было бы обойтись без этих папок, взять все и по старинке свалить в один файл, и все бы работало, но сейчас так никто не делает.
Сначала давайте рассмотрим главный файл конфигурации:

Timeout — указывает как долго сервер будет пытаться продолжить прерванную передачу или прием данных. 160 секунд будет вполне достаточно.
KeepAlive On — очень полезный параметр, позволяет передавать несколько файлов, за одно соединение, например, не только саму html страницу, но и картинки и css файлы.
MaxKeepAliveRequests 100 — максимальное количество запросов за одно соединение, чем больше, тем лучше.
KeepAliveTimeout 5 — таймаут соединения, обычно для загрузки страницы достаточно 5-10 секунд, так что больше ставить не нужно, но и рвать соединение раньше чем загрузились все данные тоже не нужно.
User, Group — пользователь и группа, от имени которых будет работать программа.
HostnameLookups — записывать в логи вместо ip адресов доменные имена, лучше отключить, чтобы ускорить работу.
LogLevel — уровень логирования ошибок. По умолчанию используется warn, но чтобы логи заполнялись медленнее достаточно включить error
Include — все директивы include отвечают за подключение рассмотренных выше конфигурационных файлов.

Директивы Directory отвечают за настройку прав доступа к той или иной директории в файловой системе. Синтаксис здесь такой:
Здесь доступны такие основные опции:
AllowOverride — указывает нужно ли читать .htaccess файлы из этой директории, это такие же файлы настроек и таким же синтаксисом. All — разрешать все, None — не читать эти файлы.
DocumentRoot — устанавливает из какой папки нужно брать документы для отображенияа пользователю
Options — указывает какие особенности веб-сервера нужно разрешить в этой папке. Например, All — разрешить все, FollowSymLinks — переходить по символическим ссылкам, Indexes — отображать содержимое каталога если нет файла индекса.
Require — устанавливает, какие пользователи имеют доступ к этому каталогу. Require all denied — всем запретить, Require all granted — всем разрешить. можно использовать вместо all директиву user или group чтобы явно указать пользователя.
Order — позволяет управлять доступом к директории. Принимает два значения Allow,Deny — разрешить для всех, кроме указанных или Deny,Allow — запретить для всех, кроме указанных. Теперь мы можем запретить доступ к директории для всех: Deny from all, а затем разрешить только для приложения от losst.ru: Allow from losst.ru.
Здесь все эти директивы не используются, поскольку нас устраивают значения по умолчанию, но вот в файлах .htaccess они могут быть очень полезны.
У нас остался файл /etc/apache2/ports.conf:

В нем только одна директива, Listen, которая указывает программе на каком порту нужно работать.
Последний файл /etc/apache2/envvars, его вы вряд ли будете использовать, в нем указанны переменные, которые можно использовать в других конфигурационных файлах.

Дальше поговорим немного о htacess. Совсем немного.
Проблема установки Apache под Windows
Основная проблема установки Web-сервера Apache под Windows заключается в том, что после первичной установки дистрибутива весь пакет (исполняемые программы, конфигурационные файлы, файлы журналов работы сервера и файловая область для размещения Web-страниц) размещается в одном месте. Это мешает нормальной эксплуатации продукта по следующим причинам:
- Разграничение прав доступа. Исполняемые файлы должны оставаться неизменными, конфигурационными файлами управляет администратор Web-сервера, а доступ к файловой области Web-страниц должны иметь разработчики и администраторы сайта. Права доступа к папке «Program Files» настроены в предположении, что в ней хранятся исполняемые модули программных пакетов, модификация которых не требуется.
- Захламление системных папок. Папка «Program Files» операционной системы Windows изначально предназначена для размещения только исполняемых файлов. Она может находиться на отдельном томе, размер которого выбирается системным администратором в предположении о его относительном постоянстве. Уж точно никто не ожидает, что в этой папке будут храниться пользовательские данные, галереи рисунков и файловый архив сайта.
Поэтому установка Apache под Windows должна проводиться в два этапа:
- Первичная установка программного пакета в выбранную папку.
- Оптимизация размещения файловых областей web-сервера и соответствующее изменение его конфигурации.
При модификации конфигурационных файлов Apache нужно постоянно помнить, что в качестве разделителя путей к файлам и папкам должен использоваться символ «прямой слеш», как в операционных системах Unix и Linux, а не «обратный слеш», как в Windows.
Создаём ссылки с нескольких DNS адресов на один сайт
Это можно осуществить двумя способами: созданием синонимов, или перенаправлением всех обращений с другого сайта.
1) Синонимы задаются директивой ServerAlias, могут содержать маску, и разделяются пробелом. Вот несколько примеров создания синонимов:
ServerAlias www.teo.mynetwork.ru ServerAlias *.teo.mynetwork.ru ServerAlias www.teo.mynetwork.ru god.mynetwork.ru pantheon.ru
Синоним — это DNS-имя. Имена могут быть абсолютно любыми, в том числе и из разных доменов, но все они должны разрешаться в IP-адреса, то есть их предварительно нужно зарегистрировать в DNS.
2) Перенаправление задаётся директивой Redirect. Создаём новый пустой сайт pantheon.ru. Как и для предыдущих сайтов, это делается в три шага: создание каталога для документов, для журналов и добавление конфигурации в httpd.conf:
<VirtualHost pantheon.ru>
DocumentRoot /var/www/html/pantheon
ServerName pantheon.ru
ErrorLog /var/log/httpd/pantheon/error_log
CustomLog /var/log/httpd/pantheon/access_log combined
Redirect / http://teo.mynetwork.ru
</VirtualHost>
Можно перенаправлять не со всего сайта, а только с определённого каталога или даже документа:
Redirect /samag http://samag.ru Redirect /ftp/ ftp://citkit.ru/pub/ Redirect /find/ya.htm http://yandex.ru
При этом Apache воспринимает первый параметр директивы Redirect не как URL, а как набор символов, при совпадении с которым происходит перенаправление. Отсюда следует, что он НЕ проверяет наличие указанных каталогов и файлов, а ссылки /samag и /samag/ НЕ считает одинаковыми.
Перенаправление с помощью файла .htaccess выглядит так:
RewriteEngine On RewriteRule ^wiki/(.*)$ http://new.site.ru/wiki/$1 RewriteRule ^(.*)$ http://new.site.ru/
- 1-я строка: включаем возможность менять URL
- 2-я строка: перенаправляем запрос к странице http://old.site.ru/wiki/Что-то на другой сайт, передавая параметры ($1)
- 3-я строка: любые другие запросы к старому сайту перенаправляем на новый.
Полезная ссылка:
http://www.portlet.ru/articles/webtips/redirect.html
Apache и другие веб-сервера
Кроме Apache существует ещё довольно много веб-серверов. Каждое приложение веб-сервера создавалось для различных целей. Не смотря на то, что Apache является самый широко используемым, для него есть несколько альтернатив и конкурентов.
Apache или NGINX

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

Tomcat – это веб-сервер также разработанных Apache Software Foundation, поэтому его официальное название Apache Tomcat. Это тоже HTTP-сервер, однако он обрабатывает приложения Java вместо статических сайтов. Tomcat может запускать несколько Java спецификаций, таких как: Java Servlet, Java Server Pages (JSP), Java EL и WebSocket.
- Tomcat был разработан специально для приложений на Java, в то время как Apache позиционируется как HTTP-сервер. Вы можете использовать Apache совместно с другими языками программирования (PHP, Python, Perl и т.д.) с помощью специального модуля Apache (mod_php, mod_python, mod_perl и др.).
- Хотя вы и можете использовать сервер Tomcat для статических веб-страниц, но это будет менее эффективно, чем использование Apache. Например, Tomcat заранее загружает виртуальную машину Java и другие Java-библиотеки, которые могут быть ненужными для работы вашего сайта.
- Tomcat также хуже настраиваемых в сравнении с другими веб-серверами. Например, для запуска WordPress, лучшим выбором будет стандартный HTTP-сервер, такой как Apache или NGINX.
Протокол TCP / IP
TCP / IP — это фактически два протокола, построенные один
поверх другого. IP-протокол
отвечает за передачу переданных данных из одной точки в другую. Он
переносит данные между двумя точками, разбивает их на меньшие пакеты,
присоединяет исходный и целевой адреса к каждому пакету и передает данные.
TCP обрабатывает часть, которая включает установление
соединения между двумя сторонами, следя за тем, чтобы данные доходили до места
назначения, заботясь о любой потере данных и управлении восстановлением данных.
После получения сообщения сторона-получатель отправляет сообщение с подтверждением (ACK) отправителю, если все идет хорошо, сообщая ему о прибытии данных. Если
что-то пойдет не так, как, например, возникновение ситуации с потерей данных,
адресат отправляет сообщение Not Acknowledged (NAK), сообщая об этом
отправляющему узлу проблемы и информируя его о необходимости повторной передачи
пакета данных.
Как
обсуждалось ранее, Apache предлагает множество сервисов, с которыми клиенты
могут захотеть подключиться, чтобы использовать или извлекать выгоду. TCP
управляет каждой службой, так что к ней осуществляется доступ через
определенный порт для различения различных служб. Таким
образом, он гарантирует, что любой данный интерфейс (или хост) может предлагать
несколько сервисов. .
Поэтому, когда клиент подключается к хосту, он передает номер порта вместе с
IP-адресом. Браузеры
используют протокол HTTP, который по умолчанию использует порт 80, поэтому нет
необходимости в дальнейшей спецификации.
Следующее
изображение представляет собой быстрый снимок моего FTP-программного
обеспечения (WinScp). Как вы видите, для FTP-сервера мне не только нужно указать IP-адрес (или ввести имя домена), но мне также необходимо указать номер порта,
через который мой сервер предоставляет услугу. В случае FTP номер порта равен 21. В
случае SFTP (защищенный FTP) номер порта равен 22.
В UNIX список сервисов, предлагаемых вместе со своими номерами портов, можно найти в файле / etc / services. Следующая
команда отобразит содержимое файла:
Ниже
приведен снимок экрана с частью файла. Как вы
можете видеть, сервисы перечислены в первом столбце, за которым следует номер
порта, к которому нужно получить доступ, и имя протокола, используемого
службой.
Под окнами файл называется Services, и его можно найти в
папке C: \ WINNT \ system32 \ drivers \ etc \
Access control by host
If you wish to restrict access to portions of your site based on the
host address of your visitors, this is most easily done using
.
The
provides a variety of different ways to allow or deny access to
resources. In conjunction with the , , and directives, these
requirements may be combined in arbitrarily complex ways, to enforce
whatever your access policy happens to be.
The ,
, and
directives,
provided by , are deprecated and
will go away in a future version. You should avoid using them, and
avoid outdated tutorials recommending their use.
The usage of these directives is:
Require host address Require ip ip.address
In the first form, address is a fully qualified
domain name (or a partial domain name); you may provide multiple
addresses or domain names, if desired.
In the second form, ip.address is an IP address, a
partial IP address, a network/netmask pair, or a network/nnn CIDR
specification. Either IPv4 or IPv6 addresses may be used.
See for further examples of this
syntax.
You can insert to negate a particular requirement.
Note, that since a is a negation of a value, it cannot
be used by itself to allow or deny a request, as not true
does not constitute false. Thus, to deny a visit using a negation,
the block must have one element that evaluates as true or false.
For example, if you have someone spamming your message
board, and you want to keep them out, you could do the
following:
<RequireAll>
Require all granted
Require not ip 10.252.46.165
</RequireAll>
Visitors coming from that address ()
will not be able to see the content covered by this directive. If,
instead, you have a machine name, rather than an IP address, you
can use that.
Require not host host.example.com
And, if you’d like to block access from an entire domain,
you can specify just part of an address or domain name:
Require not ip 192.168.205 Require not host phishers.example.com moreidiots.example Require not host gov
How directives are applied
The configuration directives found in a file
are applied to the directory in which the file
is found, and to all subdirectories thereof. However, it is important
to also remember that there may have been files
in directories higher up. Directives are applied in the order that they
are found. Therefore, a file in a particular
directory may override directives found in files
found higher up in the directory tree. And those, in turn, may have
overridden directives found yet higher up, or in the main server
configuration file itself.
Example:
In the directory we have a
file containing the following:
Options +ExecCGI
(Note: you must have «» in effect
to permit the use of the «» directive in
files.)
In the directory we have
a file containing:
Options Includes
Because of this second file, in the directory
, CGI execution is not
permitted, as only is in effect, which
completely overrides any earlier setting that may have been in
place.
Merging of .htaccess with the main
configuration files
As discussed in the documentation on Configuration Sections,
files can override the sections for
the corresponding directory, but will be overridden by other types
of configuration sections from the main configuration files. This
fact can be used to enforce certain configurations, even in the
presence of a liberal setting. For example, to
prevent script execution while allowing anything else to be set in
you can use:
<Directory "/www/htdocs">
AllowOverride All
</Directory>
<Location "/">
Options +IncludesNoExec -ExecCGI
</Location>
Configuration Files and Directives
The Apache HTTP Server is configured via simple text files.
These files may be located any of a variety of places, depending on how
exactly you installed the server. Common locations for these files may
be found in
the httpd wiki. If you installed httpd from source, the default
location of the configuration files is
. The default configuration file is
usually called . This, too, can vary in
third-party distributions of the server.
The configuration is frequently broken into multiple smaller files,
for ease of management. These files are loaded via the directive. The names or locations of
these sub-files are not magical, and may vary greatly from one
installation to another. Arrange and subdivide these files as
makes the most sense to you. If the file arrangement
you have by default doesn’t make sense to you, feel free to rearrange it.
The server is configured by placing configuration directives in these
configuration files. A directive is a keyword followed by one or more
arguments that set its value.
The question of «Where should I put that
directive?» is generally answered by considering where you want a
directive to be effective. If it is a global setting, it should appear
in the configuration file, outside of any , , , or other section. If it is to
apply only to a particular directory, then it should go inside a
section referring to
that directory, and so on. See the Configuration
Sections document for further discussion of these sections.
Basic SSI directives
SSI directives have the following syntax:
It is formatted like an HTML comment, so if you don’t have
SSI correctly enabled, the browser will ignore it, but it will
still be visible in the HTML source. If you have SSI correctly
configured, the directive will be replaced with its
results.
The function can be one of a number of things, and we’ll talk
some more about most of these in the next installment of this
series. For now, here are some examples of what you can do with
SSI
Today’s date
The function just spits out the value of a
variable. There are a number of standard variables, which
include the whole set of environment variables that are
available to CGI programs. Also, you can define your own
variables with the function.
If you don’t like the format in which the date gets printed,
you can use the function, with a
attribute, to modify that formatting.
Including the results of a CGI program
This is one of the more common uses of SSI — to output the
results of a CGI program, such as everybody’s favorite, a «hit
counter.»
Log Files and Troubleshooting
As an Apache HTTP Server administrator, your most valuable assets are
the log files, and, in particular, the error log. Troubleshooting any
problem without the error log is like driving with your eyes closed.
The location of the error log is defined by the directive, which may be set globally,
or per virtual host. Entries in the error log tell you what went wrong,
and when. They often also tell you how to fix it. Each error log message
contains an error code, which you can search for online for even more
detailed descriptions of how to address the problem. You can also
configure your error log to contain a log ID which you can then
correlate to an access log entry, so that you can determine what request
caused the error condition.
Running Apache as a Console Application
Running Apache as a service is usually the recommended way to
use it, but it is sometimes easier to work from the command line,
especially during initial configuration and testing.
To run Apache from the command line as a console application,
use the following command:
Apache will execute, and will remain running until it is stopped
by pressing Control-C.
You can also run Apache via the shortcut Start Apache in Console
placed to during the installation.
This will open a console window and start Apache inside it. If you
don’t have Apache installed as a service, the window will remain
visible until you stop Apache by pressing Control-C in the console
window where Apache is running in. The server will exit in a few
seconds. However, if you do have Apache installed as a service, the
shortcut starts the service. If the Apache service is running
already, the shortcut doesn’t do anything.
If Apache is running as a service, you can tell it to stop by opening another console
window and entering:
Running as a service should be preferred over running in a
console window because this lets Apache end any current operations
and clean up gracefully.
But if the server is running in a console window, you can
only stop it by pressing Control-C in the same window.
You can also tell Apache to restart. This forces it to reread
the configuration file. Any operations in progress are allowed to
complete without interruption. To restart Apache, either press
Control-Break in the console window you used for starting Apache,
or enter
if the server is running as a service.
Note for people familiar with the Unix version of Apache:
these commands provide a Windows equivalent to and . The
command line option used, , was chosen as a reminder
of the command used on Unix.
If the Apache console window closes immediately or unexpectedly
after startup, open the Command Prompt from the Start Menu —>
Programs. Change to the folder to which you installed Apache, type
the command , and read the error message. Then
change to the logs folder, and review the
file for configuration mistakes. Assuming httpd was installed into
,
you can do the following:
Then wait for Apache to stop, or press Control-C. Then enter the
following:
When working with Apache it is important to know how it will
find the configuration file. You can specify a configuration file
on the command line in two ways:
-
specifies an absolute or relative path to
a particular configuration file:or
-
specifies the installed Apache service
whose configuration file is to be used:
In both of these cases, the proper
should be set in
the configuration file.
If you don’t specify a configuration file with
or , Apache will use the file name compiled into the
server, such as . This built-in path
is relative to the installation directory. You can verify the compiled
file name from a value labelled as when
invoking Apache with the switch, like this:
Apache will then try to determine its by trying the following, in this order:
- A directive
via the command line switch. - The switch on the command line.
- Current working directory.
- A registry entry which was created if you did a binary
installation. - The server root compiled into the server. This is by default, you can verify it by using and looking for a value labelled as
.
If you did not do a binary install, Apache will in some
scenarios complain about the missing registry key. This warning can
be ignored if the server was otherwise able to find its
configuration file.
Configuring your server to permit SSI
To permit SSI on your server, you must have the following
directive either in your file, or in a
file:
Options +Includes
This tells Apache that you want to permit files to be parsed
for SSI directives. Note that most configurations contain
multiple directives
that can override each other. You will probably need to apply the
to the specific directory where you want SSI
enabled in order to assure that it gets evaluated last.
Not just any file is parsed for SSI directives. You have to
tell Apache which files should be parsed. There are two ways to
do this. You can tell Apache to parse any file with a
particular file extension, such as , with
the following directives:
AddType text/html .shtml AddOutputFilter INCLUDES .shtml
One disadvantage to this approach is that if you wanted to
add SSI directives to an existing page, you would have to
change the name of that page, and all links to that page, in
order to give it a extension, so that those
directives would be executed.
The other method is to use the directive:
XBitHack on
tells Apache to parse files for SSI
directives if they have the execute bit set. So, to add SSI
directives to an existing page, rather than having to change
the file name, you would just need to make the file executable
using .
A brief comment about what not to do. You’ll occasionally
see people recommending that you just tell Apache to parse all
files for SSI, so that you don’t have to
mess with file names. These folks have
perhaps not heard about . The thing to
keep in mind is that, by doing this, you’re requiring that
Apache read through every single file that it sends out to
clients, even if they don’t contain any SSI directives. This
can slow things down quite a bit, and is not a good idea.
Of course, on Windows, there is no such thing as an execute
bit to set, so that limits your options a little.
In its default configuration, Apache does not send the last
modified date or content length HTTP headers on SSI pages,
because these values are difficult to calculate for dynamic
content. This can prevent your document from being cached, and
result in slower perceived client performance. There are two
ways to solve this:
Разные серверы для статического и динамического контента
Процессы Apache, которые управляют динамическим контентом, потребляют от 3 до 20 Мб памяти. Статический контент требуют всего лишь 1Мб памяти. Процесс, управляющий динамическим контентом, при следующем запросе может предоставлять статический контент.
Что приводит к расходам памяти и замедлению работы сервера. Поэтому рекомендуется разделить серверы на управляющие статическим контентом и динамическим контентом.
Например, можно использовать небольшой Apache в качестве frontend-сервера, предоставляющего статический контент. Запросы на динамический контент будут перенаправляться к другому серверу Apache со всеми необходимыми модулями.
Для подобного перенаправления запросов используются модули mod_proxy и mod_rewrite. Клиент не заметит разницы, и будет считать, что все запросы выполняются одним сервером.
Используя два сервера, можно ускорить работу Apache, выдавая статический контент быстрее и выделяя большее количество памяти для обработки динамического контента.
Проверяем доступность страницы с других компьютеров и настраиваем брандмауэр
Снова пробуем открыть знакомую нам страницу http://192.168.0.189 (у вас цифры другие) но уже с любого другого компьютера в локальной сети.
Если вместо знакомой страницы вы увидели «Не удается получить доступ к сайту» или аналогичное сообщение — выполним настроку брандмауэра. Для этого возвращаемся на тот компьютер, где установлен Apache, заходим в «Панель управления» — «Система и безопасность» — «Брандмауэр Windows» и в левой части экрана щелкаем на «Дополнительные параметры
Кликаем на раздел «Правила для входящих подключений», затем в правой части окна «Создать правило»
Выбираем «Для порта» — Далее, Протокол TCP, Опреленные локальные порты: 80, Далее

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

Указываем произвольное имя, например «Веб сервер 80 порт для 1С». Готово.
Снова идем на другие компьютеры и убеждаемся, что теперь по IP адресу http://192.168.0.189 броузер показывает знакомую нам страницу It Works
Name-based hosts on more than one IP address.
Note
Any of the techniques discussed here can be extended to any
number of IP addresses.
The server has two IP addresses. On one (), we
will serve the «main» server, and on the
other (), we will serve two or more virtual hosts.
Listen 80
# This is the "main" server running on 172.20.30.40
ServerName server.example.com
DocumentRoot "/www/mainserver"
<VirtualHost 172.20.30.50>
DocumentRoot "/www/example1"
ServerName www.example.com
# Other directives here ...
</VirtualHost>
<VirtualHost 172.20.30.50>
DocumentRoot "/www/example2"
ServerName www.example.org
# Other directives here ...
</VirtualHost>
Hostnames and DNS
In order to connect to a server, the client will first have to resolve
the servername to an IP address — the location on the Internet where the
server resides. Thus, in order for your web server to be reachable, it
is necessary that the servername be in DNS.
If you don’t know how to do this, you’ll need to contact your network
administrator, or Internet service provider, to perform this step for
you.
More than one hostname may point to the same IP address, and more
than one IP address can be attached to the same physical server. Thus, you
can run more than one web site on the same physical server, using a
feature called virtual hosts.
If you are testing a server that is not Internet-accessible, you
can put host names in your hosts file in order to do local resolution.
For example, you might want to put a record in your hosts file to map a
request for to your local system, for
testing purposes. This entry would look like:
A hosts file will probably be located at or
.
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.
Копирование числовых ячеек из 1С в Excel Промо
Решение проблемы, когда значения скопированных ячеек из табличных документов 1С в Excel воспринимаются последним как текст, т.е. без дополнительного форматирования значений невозможно применить арифметические операции. Поводом для публикации послужило понимание того, что целое предприятие с более сотней активных пользователей уже на протяжении года мучилось с такой, казалось бы на первый взгляд, тривиальной проблемой. Варианты решения, предложенные специалистами helpdesk, обслуживающими данное предприятие, а так же многочисленные обсуждения на форумах, только подтвердили убеждение в необходимости описания способа, который позволил мне качественно и быстро справиться с ситуацией.
MPM Configuration
HTTP/2 is supported in all multi-processing modules that come with httpd. However, if
you use the mpm, there will be severe restrictions.
In , will only process one request at at time
per connection. But clients, such as browsers, will send many requests at the same time.
If one of these takes long to process (or is a long polling one), the other requests will
stall.
will not work around this limit by default. The reason is that
is today only chosen, if you run processing engines that are not
prepared for multi-threading, e.g. will crash with more than one request.
If your setup can handle it, configuring mpm is nowadays
the best one (if supported on your platform).