Софт

Apache 2 windows

Рейтинг: 4.7/5.0 (568 проголосовавших)

Категория: Windows: Web серверы

Описание

Установка Apache PHP MySQL под Windows - Apache

Установка Apache+PHP+MySQL под Windows - Apache

07.01.2010, 15:12 Установка Apache+PHP+MySQL под Windows

Очень часто у людей возникают сложности с установкой Apache+PHP+MySQL. В результате начинают использовать всякие глючные сборки типа Денвера и т.п. Предлагаю подробную инструкцию, как установить Apache, PHP и MySQL самому и без лишних проблем. Я постарался написать её как можно проще для понимания.

Вначале нужно скачать все эти программы. Скачивать лучше всего с их официальных сайтов, т.к. это и безопаснее (точно нет вирусов) и вы сможете использовать последние версии.

Несколько слов про PHP. установочные файлы под Windows находятся на http://windows.php.net/download/ Выбирать там нужно тот, который VC6 x86 Thread Safe. VC9 под Apache не подходит.

В этой инструкции я использовал последнии версии, существующие сегодня (Apache 2.2.14, PHP 5.3.1 и MySQL 5.1.42). Но и с более современными версиями всё должно быть так же.

Установка Apache

Запускаем установщик apache_2.2.14-win32-x86-openssl-0.9.8k.msi

Вначале появится просто окно приветствия. нажимаем кнопку "Next"

Потом соглашаемся с лицензионным соглашением.

Потом нам покажут небольшую информацию об Апаче. опять идём дальше.

Тут нас просят имя домена, имя сервера и e-mail администратора. На первое время, это не имеет никакого значения. А если потом потребуется, то можно будет настроить. Пока домен и имя сервера назовём именем этого компьютера (в моём случае имя компьютера "test"). E-mail админа вообще не имеет значения. он отображается только при сообщениях об ошибках (например, если не найдена страница, запрещён доступ и т.п.). Ниже он справшивает, на какой порт настроить сервер. оставляем на 80 (это стандартный порт для веб-серверов).

На следующей странице нас спрашивают, как устанавливать: Typical или Custom. Выбираем Typical.

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

На следующей странице нажимаем кнопку "Install"

Всё. Веб-сервер Apache установлен. Что бы проверить, открываем браузер и заходим на http://127.0.0.1 (я рекомендую использовать именно IP адрес 127.0.0.1. а не localhost. Т.к. иногда по каким-то причинам у некоторых пользователей имя localhost бывает не указано в файле \WINDOWS\system32\drivers\etc\hosts, что приводит к лишней трате времени).

Должна появиться надпись "It works!". значит сервер работает.

Установка PHP

Запускаем файл php-5.3.1-Win32-VC6-x86.msi

Нажимаем "Next"

Соглашаемся с лицензией

Указываем папку, куда нужно устанавливать

Дальше установщик спросит, какой у вас установлен веб-сервер. Выбираем Apache 2.2x Module

Потом спросит, в какой папке находится файл с настройками Апача (файл называется httpd.conf ). Он находится в папке C:\Program Files\Apache Software Foundation\Apache2.2\conf

На следующей странице попросит выбрать компоненты, которые нужно установить. можно оставить всё как предлагает.

Нажимаем кнопку "Install"

PHP сам настроит Апач должным образом. а именно добавит в конец файла httpd.conf строки

Apache 2 windows:

  • скачать
  • скачать
  • Другие статьи, обзоры программ, новости

    How to install Apache 2 web server on Windows to create a web development environment

    Steps to install Apache on Windows as development machine

    Here is a list of Apache HTTP server related pages:

    Step 1: Download Apache 2.2

    In this article, we use Apache 2.2.14 to demonstrate the installation process. Other 2.x versions have very similar installation steps.

    (2) Download Apache 2.2.14 msi installer.

    Step 2: Verify the downloaded file for integrity

    Apache download comes with a MD5 hash value. This hash value is a Checksum value that can be used to verify data and file integrity.
    • File to verify: apache_2.2.14-win32-x86-no_ssl.msi
    • Link from Apache to obtain the MD5 hash of this file:

    MD5 hash obtained from Apache.org for this file: e41bf079b88265d733a559f33c559ce6

    Screenshot below shows the Apache installation file was verified by freeware HashCalc .

    Checksum calculated by HashCalc:

    As we see above, the MD5 checksum value by Apache.org is the same as the one calculated by HashCalc, which means the file is in good shape and can be trusted.

    Step 3: Start installation

    Double click the installation file. The installation should start straight away. Here are 9 screenshots.

    3.1 Welcome

    3.2 License Agreement

    3.3 Read First

    3.4 Server Information

    This step needs a bit explanation. Add localhost to both Network Domain and Server Name box. Administrator's Email Address can be anything you like. These info are used for Apache configuration file but you can change them after the installation.

    Next, select the first radio button as recommended. This way, Apache will be running as a Windows Service. See Step 6 below for more info about how to start, stop, restart Apache.

    3.5 Setup Type

    Choose Typical as the setup type.

    3.6 Destination Folder

    You can leave the default installation folder as is.

    3.7 Ready to install

    3.8 Installing in progress

    3.9 Completed successfully

    Step 4: Test your installation

    After install, open web browser and type either of the following URLs into your browser's address bar and hit Enter key.

    1. http://localhost
    2. http://127.0.0.1
    3. http://169.254.32.57 or 192.168.0.1 (eg. local network IP address)

    If Apache has been installed correctly, you should see a success message opened in your web browser, as shown below.

    The text actually comes from the index.html file in this directory C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\ which is the default document root directory after Apache is first installed. The document root directory can be changed in Apache configuration file. See Step 5 below.

    Note: http://169.254.32.57 could be your local machine's auto assigned IP that Microsoft has reserved (addresses 169.254.00 to 169.254.255.255).

    If you use a router which sets up a LAN (Local Area Network), the router can assign an internal IP. For example, Linksys assumes a default internal IP address of 192.168.0.1

    To find out your computer's IP address, open a command line window and run ipconfig command:

    • Click Start
    • Click Run
    • In the Run command box, type cmd and hit OK
  • When command line window is opened, type ipconfig and hit Enter key.

    Step 5: Edit the Apache httpd.conf Configuration File

    Apache Configuration File is located at C:\Program Files\Apache Software Foundation\Apache2.2\conf\httpd.conf. It can also be opened from the Start menu as below.

    Make sure you change the httpd.conf file according to the screenshots shown in the following section.

    5.1 Change your document root directory to a more meaningful one.

    Inside the configuration file, DocumentRoot is the directory out of which Appache executes web documents, eg. PHP, HTML, etc. It's the directory where your PHP or other web page files are placed into.

    1. Commented out DocumentRoot "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs"

    2. and then added DocumentRoot "C:/test"

    So, all my php files will be located in a folder named as test on my C drive.

    3. Commented out <Directory "C:/Program Files/Apache Software Foundation/Apache2.2/htdocs">

    4. and then added <Directory "C:\test">

    5.2 Add PHP file type into DirectoryIndex

    Add the default document file names that Apache will run if we don't type its filename in web browser.

    Edit the line as below shows, ie. DirectoryIndex index.html index.htm index.php

    5.3 If you need to rewrite URLs on your site, enable the mod_rewrite module.

    Web pages can pass variables in URLs and this is known as dynamic URLs. To make these URLs search engine and user friendly, we often change dynamic URLs to static URLs. This change is managed by the URL rewrite module.

    To enable the URL rewrite, follow these 2 steps.

    • Find the line of text shown below and remove the hash # at the beginning of the line.

    #LoadModule rewrite_module modules/mod_rewrite.so

    Here is how it looks after the change is made.

  • Change AllowOverride None to AllowOverride All inside the DocumentRoot Directory Directive.

    In our case, it is inside <Directory "C:\test"> Directive.

    Here is how it looks after the change is made.

    If you need to modify Hosts file, please note that Windows Vista and Windows 7 have stricter security mechanism that makes changing the hosts file a lot harder. Please refer to Microsoft Knowledge Base article http://support.microsoft.com/kb/923947 to see how to modify the Hosts file in Windows Vista and Windows 7.

    Step 6: Restart Apache

    After changing Apache configuration file, remember restart Apache Server so that these changes will take effect.

    To start, stop, and restart Apache Server, do this: Start -> Programs -> Apache HTTP Server -> Control Apache Server.

    If Control Apache Server menu is not available. You can start, stop, and restart Apache by using Microsoft Management Console for Windows Services.

    Start -> Settings -> Control Panel -> Administrative Tools -> Services

    By using Windows Services, you can Start, Stop, and Restart Apache from Microsoft Management Console. See screenshot below. Selecting Apache as a Windows service will make it automatically start when your computer starts up, and to keep Apache running when you log-off.

    Happy Installing!

    Copyright© GeeksEngine.com

  • PHP - Apache 2

    Apache 2.x on Microsoft Windows

    Этот раздел содержит инструкции по установке PHP для Apache 2.x на системы Microsoft Windows. Мы также имеем инструкции для пользователей Apache 1.3.x на отдельной странице.

    Замечание.

    Замечание. Поддержка Apache 2.2

    Пользователям Apache 2.2 следует отметить, что DLL файл для Apache 2.2 называется php5apache2_2.dll. а не php5apache2.dll и он доступен только для PHP 5.2.0 и более поздних версий. Смотрите также » http://snaps.php.net/

    Вам настоятельно рекомендуется ознакомиться с » Документацией по Apache. чтобы получить базовые знания о Apache 2.x Server. Также перед чтением данной справки обратите внимание на » Рекомендации для Windows по Apache 2.x.

    Apache 2.x предназначен для работы в серверных версиях Windows, таких как Windows NT 4.0, Windows 2000, Windows XP или Windows 7. Хотя Apache 2.x может использоваться на Windows 9x, эти платформы не поддерживаются полностью, и некоторые функции не будут работать правильно. Исправление этой ситуации не планируется.

    Скачайте наиболее актуальную версию » Apache 2.x и подходящую версию PHP. Следуйте Пошаговому руководству по установке и вернитесь для продолжения интеграции PHP и Apache.

    Существует три пути установки PHP для Apache на Windows. Вы можете запустить PHP как обработчик, как CGI, или под FastCGI.

    Замечание. Помните, что при указании путей в конфигурационных файлах Apache под Windows, все обратные слэши, например, c:\directory\file.ext должны быть изменены на прямые: c:/directory/file.ext. Для путей с директориями также может понадобиться слэш в конце.

    Установка PHP как обработчика под Apache

    Вам необходимо добавить следующие строки в ваш конфигурационный файл Apache httpd.conf для загрузки PHP-модуля для Apache 2.x:

    Пример #1 PHP как обработчик Apache 2.x

    Виртуальные хосты в Apache2 (Windows)

    Виртуальные хосты в Apache2 (Windows) Терминология:
    • Хост (от англ. host — хозяин, принимающий гостей) — любое устройство, предоставляющее сервисы формата «клиент-сервер» в режиме сервера по каким-либо интерфейсам и уникально определённое на этих интерфейсах. В более частном случае под хостом могут понимать любой компьютер, сервер, подключённый к локальной или глобальной сети.
    • Доме?н, доме?нное имя — это имя, служащее для идентификации областей — единиц административной автономии в сети Интернет — в составе вышестоящей по иерархии такой области. Каждая из таких областей называется доме?ном. Общее пространство имён Интернета функционирует благодаря DNS — системе доменных имён. Доменные имена дают возможность адресации интернет-узлов и расположенных на них сетевых ресурсов (веб-сайтов, серверов электронной почты, других служб) в удобной для человека форме.
    • URL (англ. Uniform Resource Locator) — единообразный локатор (определитель местонахождения) ресурса. URL — это стандартизированный способ записи адреса ресурса в сети Интернет.
    • Термин виртуальный хост относится к практике размещения более чем одного веб-сайта (например, www.company1.com и www.company2.com) на одной машине. Виртуальный хост может быть как «привязанным к IP-адресу», что означает использование отдельного IP адреса для каждого сайта, либо «привязанным к имени», позволяя вам иметь несколько различных имён для каждого IP-адреса. Факт того, что эти сайты работают на одном и том же физическом сервере, не очевиден конечным пользователям.
    • hosts — текстовый файл, содержащий базу данных доменных имен и используемый при их трансляции в сетевые адреса узлов. Запрос к этому файлу имеет приоритет перед обращением к DNS-серверам. В отличие от DNS, содержимое файла контролируется администратором компьютера.
    • Профит

    Если бы мы просто расположили файлы проекта в папке ..\Apache2\htdocs\projectname. то единственный доступный URL для проекта - был бы http://localhost/projectname/. Сложилась у нас ситуация, например, что в контенте проекта ссылки генерируются не относительно папки проекта, а указаны относительно корня домена ("/url " вместо "/projectname/url "). Либо мы работаем с банками шрифтов и в условиях поставки шрифта на сайт указано, что шрифт может получаться только по определенному домену. Либо ещё что. Придумайте сами :)

    Смонтировать папку, лежащую не в ..\Apache2\htdocs и дать апачу понять, что мы хотим чтобы проект из этой папки выступал в качестве отдельного хоста без подпапок (виртуального домена). То есть чтобы зайдя на http://projectname.localhost/ у нас запустился бы проект из определенной папки (и ссылки вида "/url" заработали, или шрифты подгрузились, или всё то что вы придумали сами).

    1. Добавляем разрешения на папку с проектами и добавляем сам виртуальный хост:

    Чтобы виртуальный хост мог подхватить папку - необходимо дать понять веб-серверу с какими привилегиями мы можем использовать папку и все подпапки D:\Projects. В будущем не будет необходимости добавлять подпапки для каждого проекта, нужно лишь единожды указать папку с расположенными в ней проектами.

    Обратите внимание на projectname.localhost:80. 80 - это порт, по которому будет доступен проект. Так на одном хосте (или виртуальном хосте) можно крутить несколько проектов на разрых портах.  Например:

    • http://localhost:80/ - папка. \Apache2\htdocs
    • http://localhost:81/ - другая папка, указанная в конфигурации виртуального хоста

    В виртуальный хост можно пихнуть ещё много вкусностей. Все возможности конфигурации виртуальных хостов можно посмотреть в официальной документации .

    Внимание! Чтобы Apache2 подхватил наши изменения в конфигурационном файле - его необходимо перезапустить. Это можно сделать как через трей. так и через управление службами Windows.

    2. Говорим системе, что при обращении к виртуальному хосту - перенаправлять на локальный хост:

    Apache Web Server for Windows

    Building Apache 2.2.3 or 2.0.59, with mod_ssl, mod_security, mod_deflate Building a Web Server, for Windows Requirements
    • Microsoft Visual C++

    [we will use Visual Studio 98 / VC++ 6.0]

    [Visual Studio .NET will also work with the same instructions]
  • Gawk [needed for the Apache2 build process]
  • [optional] zlib. mod_deflate source
  • [optional] OpenSSL. mod_ssl source
    • Perl [native Perl, not Cygwin Perl]
    • Additional build tools: bison, flex, sed
  • [optional] mod_security source
    • Package(win32 source):
      • httpd-2.2.3-win32-src.zip -- Unpack as C:\build\httpd-2.2.3
      • httpd-2.0.59-win32-src.zip -- Unpack as C:\build\httpd-2.0.59
    • Gawk, bison, flex, sed. can be downloaded as stand alone win32 ports from GnuWin32 or with the Cygwin environment. Do not use UnxUtils.
      • Pre-packaged DeveloperSide.NET distribution of the required GnuWin32 tools: GnuWin32tools.rar [Download and add directory 'C:\GnuWin32\bin' to the PATH]
      • GnuWin32. http://gnuwin32.sourceforge.net/packages.html [Note that only Bison v1.35 will work from GnuWin32 for this build, and will require libintl-2.dll and libiconv-2.dll ]
      • Cygwin. http://cygwin.com/
    • Download zlib source code, v1.2.3, from. http://www.gzip.org/zlib/
      • Unpack as C:\build\httpd-2.x.x\srclib\zlib
    • Download OpenSSL source code, v0.9.8b, from. http://www.openssl.org/source/
      • Unpack as C:\build\httpd-2.x.x\srclib\openssl
    • Download mod_security source code, v1.9.4, from. http://www.modsecurity.org/download/index.html
      • Unpack as C:\build\modsecurity-apache-1.9.4
    Our Configuration
    • Build directory. C:\build
    • Install to:
      • Apache 2.0: C:\www\Apache2
      • Apache 2.2: C:\www\Apache22
    • System:Port. localhost:80
    • Module type. dynamically loaded modules, *.so (and *.dll)
    • [optional] Additional modules over base. mod_deflate, mod_ssl, mod_security
    • Perl.exe path. C:\www\perl\bin
    • awk, bison, flex, sed path. C:\GnuWin32\bin [Read below 'Notes' for clarification on gawk/awk]
    • System PATH. contains C:\www\perl\bin and C:\GnuWin32\bin

      [Read below 'Notes' for clarification on system path]

    • When using the command-line (command-shell) with VC++, always set the Build Environment and update the System PATH to reflect the tools used in the build --> Guide: Working with the Command Shell
    • This Guide can be used without the inclusion of modules mod_ssl, mod_security, and mod_deflate -- simply ignore the related Sections, material, and tools
    • The System PATH must contain the path to perl.exe and the other build tools
    • file 'gawk.exe' must be renamed to 'awk.exe' for the Apache2 build process
    • If using Cygwin 'gawk', delete the symlink 'awk.exe' and rename 'gawk.exe' to 'awk.exe' under. \cygwin\bin
    Setup for mod_deflate

    To build mod_deflate, the zlib source code directory is placed under C:\build\httpd-2.x.x\srclib (as httpd-2.x.x\srclib\zlib). The main Apache 2.0/2.2 build process will automatically compile the zlib source code and build mod_deflate. Note that to build zlib v1.2.3 under Apache 2.0, the C:\build\httpd-2.0.x\modules\filters\mod_deflate.dep/dsp/mak files will need to be patched. Do NOT perform this patching step if building mod_deflate under Apache 2.2, or if building against zlib v1.1.4.

    Patch mod_deflate (zlib 1.2.3) to build under Apache 2.0.

    • Download package Patch (binary zip or setup) and install, making sure that patch.exe can be located under the PATH and that libs libiconv-2.dll and libintl-2.dll are under the same directory as the patch binary.
    [the patch utility is provided under the DeveloperSide.NET GnuWin32 tools distribution]
  • Save zlib patch file as C:\build\httpd-2.0.x\zlib.patch
  • . \httpd-2.0.x> patch -p1 < zlib.patch
  • [Optional] Build zlib with ASM options.

    • . \httpd-2.x.x\srclib\zlib\contrib\masmx86> mkasm.bat
    • Copy files gvmat32.obj, inffas32.obj, gvmat32c.obj to the base zlib directory.
    • . \httpd-2.x.x\srclib\zlib> nmake -f win32\Makefile.msc LOC="-DASMV -DASMINF" OBJA="gvmat32c.obj gvmat32.obj inffas32.obj"
    Setup for mod_ssl

    To build mod_ssl, the OpenSSL source code directory is placed under C:\build\httpd-2.x.x\srclib (as httpd-2.x.x\srclib\openssl). The OpenSSL source is then manually compiled to prepare for the main Apache 2.0/2.2 build process.

    Configure the build.

    ['--openssldir=DIR' tells openssl.exe where to look for openssl.cnf]

    [we must use unix forward style slashes(/), instead of windows style back slashes(\)]
    • > cd /d C:\build\httpd-2.x.x\srclib\openssl
    • For Apache 2.2
    > perl Configure --openssldir=C:/www/Apache22/bin VC-WIN32
  • For Apache 2.0

    > perl Configure --openssldir=C:/www/Apache2/bin VC-WIN32

  • Use x86 assembly functions for performance improvements.

    Note that if your Compiler or System does not include MASM (ml.exe error): run 'ms\do_ms' instead.

    > ms\do_masm

    > nmake -f ms\ntdll.mak

    [optional] Test the built OpenSSL package.

    • > cd out32dll
    • >. \ms\test
    Apache 2.2.3 Patch

    The Apache 2.2.3 Windows source has problems in four projects dsp and mak files. Also, a perl script has to be run to convert the projects to the VC++ version that is being used to compile the code. Both of these problems should be fixed under Apache 2.2.4

    Download apache-2.2.3-projects.zip and extract the following 4 dsp and mak project files to the given directories.

    • modules/aaa/mod_authn_dbd.dsp\mak
    • modules/filters/mod_ext_filter.dsp\mak
    • modules/metadata/mod_usertrack.dsp\mak
    • support/htpasswd.dsp\mak

    If using VS.NET 2005 to compile Apache 2.2.3, download cvtdsp.pl and run 'perl cvtdsp.pl -2005' (For VC++ 6.0: 'perl cvtdsp.pl -6' but this is unnecessary).

    Build/Install Apache

    Apache 2.0/2.2 can be built using the command line, or with the Visual Studio Workspace IDE. The command line build is the perfered choice.

    Command-Line Build Instructions

    Build Apache 2.0/2.2 in Release mode under C:\www\Apache22 (for 2.2) or C:\www\Apache2 (for 2.0), with the server listening on localhost (127.0.0.1, your local system) on port 80 (regular HTTP port).

    • For Apache 2.2
    \httpd-2.2.x> nmake /f Makefile.win SERVERNAME="localhost" PORT=80 INSTDIR="C:\www\Apache22" installr
  • For Apache 2.0

    \httpd-2.0.x> nmake /f Makefile.win SERVERNAME="localhost" PORT=80 INSTDIR="C:\www\Apache2" installr

  • Visual Studio Workspace IDE Build Instructions

    Apache.dsw is the Visual Studio workspace, which exposes the entire list of working .dsp projects that are required for the complete Apache 2.0/2.2 binary release.

    • Load Apache.dsw
    • "The project Apache.dsp needs to be converted to the Visual C++ 7.0 project format"
      • Click 'Yes To All'
    • Right click 'BuildBin' under Solution Explorer
      • Select 'Set as StartUp Project'
    • Select 'Solution 'Apache'' under Solution Explorer
      • Change 'Active Config' value under Properties Window from 'Debug' to 'Release'
    • [If you are not building mod_ssl and mod_deflate] Note that by default, under the IDE build, the build process will try to build modules abs, mod_ssl, and mod_deflate. If the source code and libs of the additional modules have not been provided, the mentioned modules will need to be deselected.
      • Under the Build menu, select Configuration Manager
      • Deselect 'abs', 'mod_deflate', 'mod_ssl'
      • Click 'Close'
    • Note that with the Workspace IDE build, by default, Apache 2.0/2.2 is installed into <drive>:\Apache2. We are installing to <drive>:\www\Apache22 (for 2.2) or to <drive>:\www\Apache2 (for 2.0).
      • For 'BuildBin' and 'InstallBin' -- Right click each under Solution Explorer and perform these steps
        • Select 'Properties'
        • Select 'NMake' under 'Configurations Properties'
        • Update. 'Build Command Line', 'Rebuild All Command Line', 'Output' Replace "\Apache2\. " with "\www\Apache22\. " (for 2.2) or "\www\Apache2\. " (for 2.0)
        • Click 'OK'
    • Select 'Build Solution' under the Build menu
    Setup for mod_security

    To build mod_security, the built Apache2 libraries and include files are used.

    Edit file C:\build\modsecurity-apache-1.9.4\apache2\makefile.win and change the BASE path to the built Apache2 dir.

    • Apache 2.2
    BASE = "C:/www/Apache22/"
  • Apache 2.0

    BASE = "C:/www/Apache2/"

  • If building against Apache 2.2, edit file C:\build\modsecurity-apache-1.9.4\apache2\makefile.win and update the following line to reflect the new Apache 2.2 library names.

    • Original line
    LIBS = $(BASE)\lib\libhttpd.lib $(BASE)\lib\libapr.lib $(BASE)\lib\libaprutil.lib
  • Updated line

    LIBS = $(BASE)\lib\libhttpd.lib $(BASE)\lib\libapr-1.lib $(BASE)\lib\libaprutil-1.lib

  • Build mod_security.

    . \modsecurity-apache-1.9.4\apache2> nmake /f makefile.win

    Copy generated file mod_security.dll to dir C:\www\Apache[2,22]\modules and file mod_security.lib to dir C:\www\Apache[2,22]\lib

    Additional Steps and Information

    During the Apache 2.0/2.2 build process, the needed OpenSSL files (libeay32.dll, ssleay32.dll, openssl.exe) are placed into C:\www\Apache[2,22]\bin, except openssl.cnf. openssl.cnf is the OpenSSL configuration file. This file needs be copied manually.

    From directory. \httpd-2.x.x\srclib\openssl\apps copy file openssl.cnf to C:\www\Apache22\bin (2.2) or C:\www\Apache22\bin (2.0) [note that .cnf file extensions are invisible, by default, on Windows 2000/XP]

    Apache v2.x (win32) file ssl.conf contains a syntax problem that needs to be addressed.

    Change 'SSLMutex file:logs/ssl_mutex' under ssl.conf to 'SSLMutex default' [the default 'file:logs/ssl_mutex' option is not available under win32]

    Update Configuration Files

    Now that the Apache httpd Web-Server has been successfully built -- [before proceeding with startup] configuration file httpd.conf will need to be updated (for mod_deflate and other changes) and an SSL Private/Public Key-Pair will need to be created (for mod_ssl).

    Note that if "localhost" will be used, make sure that file %SystemRoot%\system32\drivers\etc\hosts contains line.

    127.0.0.1 <tab> localhost

    mod_deflate requires several additions and updates to be made to httpd.conf, the Apache 2.0/2.2 configuration file.

    Open C:\www\Apache[2,22]\conf\httpd.conf, add.

    The default Apache DocumentRoot/Webroot is set to. \Apache22\htdocs (for 2.2) or. \Apache2\htdocs (for 2.0) -- our Guides and our Web-Server Suite has this changed to \www\webroot -- update DocumentRoot if you are also going to use our other Guides. Note that when testing Apache, you will need to make/copy index.html and/or other files into the new directory, as it will be empty.

    Open C:\www\Apache[2,22]\conf\httpd.conf.

    Locate line DocumentRoot "/www/Apache[2,22]/htdocs". replace with.

    DocumentRoot "/www/webroot"

    Locate line <Directory "/www/Apache[2,22]/htdocs">. replace with.

    <Directory "/www/webroot">

    Startup and Operation

    Executables 'httpd.exe' (for 2.2) and 'apache.exe' (for 2.0) are located under directory 'C:\www\Apache22\bin' (for 2.2) or 'C:\www\Apache2\bin' (for 2.0) - which should be included into the System PATH. If this dir is not in the PATH, 'httpd.exe' or 'apache.exe' should be run from a command line that is under 'C:\www\Apache[2,22]\bin'.

    Install the 'Apache2' Service.

    How to Install and Configure Apache 2 on Windows ()

    How to Install and Configure Apache 2 on Windows

    Many webmasters choose to install a copy of the Apache web server on their machines so that they can test their PHP and Perl scripts before they upload it to their "live" websites. This allows them to fix any problems on their site before it actually affects their website's visitors. This article deals with how you can set up and configure Apache 2 on your own computer so that you can test your scripts and site.

    Preliminary Notes Which Version of Apache to Use

    At present, there are three major versions of Apache available: the 1.3 series, the 2.0 series and the 2.2 series. You should choose the version that matches the one used by your web host. If you are using Apache 1.3, you should probably check out my other tutorial, How to Install Apache 1.x on Windows at http://www.thesitewizard.com/archive/apache.shtml

    If You're Using Windows Vista, Windows 7 or Later

    If you're using Windows Vista, please see the How to Install Apache 2.2 on Windows Vista tutorial instead. The later versions of Windows require a different installation procedure.

    For Offline Testing

    This installation guide is meant for people who want to install Apache for private offline use, such as to test your own scripts or website on your own machine. It is not intended for you to set up a "live" website that is connected to the Internet. The instructions here do not take into account things like security or your real domain names and the like, which you will need to configure for if your server is going to be exposed to the Internet.

    Steps to Installing and Configuring Apache 2 for Windows XP Download Apache 2

    Firstly, download a copy of Apache 2. Since we are talking about Apache 2 here, be sure to scroll down the page to the appropriate section. Select the "Other files" link in that section to get a complete listing of the available Apache 2 versions. In the new page that appears, click the "binaries" folder followed by the "win32" folder. A list of files with different version numbers will be listed.

    If you want the Apache 2.0 series, and the current version of the Apache 2.0 series is, say, 2.0.61, look for the file named "apache-2.0.61-win32-x86-no_ssl.msi". Likewise if you want the Apache 2.2 series, and the current version is, say, 2.2.6, go for the file named "apache-2.2.6-win32-x86-no_ssl.msi".

    Click it and save the file to your hard disk. Remember where you saved it so that you can run it later.

    Run the Apache Installer

    When you have finished downloading the file, double-click it to run the Apache installer. Follow the instructions to install Apache.

    When you arrive at the "Server Information" dialog box, enter "localhost" (without the quotes) for the Network Domain as well as for the Server Name and whatever email address you wish for the "Administrator's Email Address" field. The installer uses the information you enter to create a default Apache configuration file for you. You can always go back and manually change these values in your configuration file if you change your mind later. Leave the default setting of "for All Users, on Port 80, as a Service" as it is. Click "Next" when you're done.

    When asked about the Setup Type, select "Typical" and click "Next".

    Allow the installer to install to the default folder in the next screen. Note that this tutorial will assume that you are using the default folder of "c:\Program Files\Apache Group\" here. Click "Next".

    Finally click the "Install" button to allow the installer to set up Apache. When it is done, click the "Finish" button.

    Enabling and Disabling the Apache Service

    The Apache installer automatically starts the Apache service when it finishes the installation. If you ever wish to stop the Apache 2 service and only start it manually when you need to use it for testing, go to Control Panel -> Administrative Tools -> Services, look for the "Apache2" service and double-click it. From here you can stop the service and change the startup type to "Manual". The Apache service will then terminate and only start when you return to this control panel applet to manually start it. This is useful if, like me, you're only using the server to test your scripts, and don't want the server running all the time.

    Changing the Server Name and Administrator's Email Address

    If you want to change the server name that you entered when you set up Apache, use the Start menu to open the Apache configuration file: you can find the appropriate item at Start -> Programs -> Apache HTTP Server -> Configure Apache Server -> Edit the Apache httpd.conf Configuration File.

    A Notepad window will open with your Apache configuration file loaded. If you ever need to load your configuration file with another ASCII editor. it can be found at "C:\Program Files\Apache Group\Apache2\conf\httpd.conf" for Apache 2.0 and "C:/Program Files/Apache Software Foundation/Apache2.2" for Apache 2.2.

    Search for the following text and replace the "localhost" with the name you want.

    ServerName localhost:80

    Likewise if you want to change the Administrator's Email Address that you entered earlier, look for a line like the following:

    ServerAdmin admin@localdomain

    The exact email address displayed will be different, depending on what you entered during the setup process earlier.

    In general, if you are just setting up Apache for private offline testing, you can basically leave these settings as they are.

    Configuring Apache to Accept Server Side Includes (SSI)

    If you want the web server to parse Server Side Includes (SSI directives). search for the text "server-side includes" in the file. Add the following lines just after the block of text containing those words:

    AddType text/html .shtml

    AddOutputFilter INCLUDES .shtml

    Alternatively, you can uncomment the example text given in the configuration file by removing the hash prefix ("#") before each line.

    Apache will now handle the SSI directives that occur in files with names ending in ".shtml".

    If you want "index.shtml" to be your default start page for your directories, ie, if you want Apache to load "index.shtml" when you type "localhost" or "localhost/directory/", you will need to search for a line in your "httpd.conf" that begins with "DirectoryIndex" and add index.shtml to the list of files there. For example, modify it as follows:

    DirectoryIndex index.shtml index.html

    Adding it before index.html means that Apache will give preference to index.shtml if both are present.

    Save the Configuration File and Restart Apache

    When you are satisfied with your changes, save the file - just use the "Save" item from the "File" menu or type Ctrl+S. After you make a configuration change, you need to restart Apache. To do this, go to the Start Menu and click the "Restart" item in the "Control Apache" folder, that is, select Start -> Programs -> Apache HTTP Server -> Control Apache Server -> Restart.

    How to Test Your Apache Server

    To test if your server is installed and configured properly, open up a browser and type "localhost" in the location bar of your browser. You should be able to see the default Apache test page.

    Where to Place Your Website

    By default, your pages should be placed in the "C:\Program Files\Apache Group\Apache2\htdocs" folder for Apache 2.0 and the "C:\Program Files\Apache Software Foundation\Apache2.2\htdocs" folder for Apache 2.2. When your site is ready, simply delete the existing files in the folder and replace them with those you want to test.

    Using Apache HTTP Server on Microsoft Windows - Apache HTTP Server Version 2

    Using Apache HTTP Server on Microsoft Windows

    Available Languages: en | ko

    This document explains how to install, configure and run Apache 2.2 under Microsoft Windows. If you have questions after reviewing the documentation (and any event and error logs), you should consult the peer-supported users' mailing list .

    Operating System Requirements

    Running Apache on Windows 9x is ignored by the developers, and is strongly discouraged. On Windows NT 4.0, installing Service Pack 6 is required. Apache HTTP Server versions later than 2.2 will not run on any operating system earlier than Windows 2000.

    Downloading Apache for Windows

    The Apache HTTP Server Project itself does not provide binary releases of software, only source code. Individual committers may provide binary packages as a convenience, but it is not a release deliverable.

    If you cannot compile the Apache HTTP Server yourself, you can obtain a binary package from numerous binary distributions available on the Internet.

    Popular options for deploying Apache httpd, and, optionally, PHP and MySQL, on Microsoft Windows, include:

    Installing Apache for Windows

    You need Microsoft Installer 2.0 or above for the installation to work. For Windows NT 4.0 and 2000 refer to Microsoft's article KB 292539. Windows XP and later do not require this update. The Windows 98/ME installer engine appears to no longer be available from Microsoft, and these instructions no longer detail such prerequisites.

    Note that you cannot install two versions of Apache 2.2 on the same computer with the binary installer. You can, however, install a version of the 1.3 series and a version of the 2.2 series on the same computer without problems. If you need to have two different 2.2 versions on the same computer, you have to compile and install Apache from the source .

    Run the Apache .msi file you downloaded above. The installation will ask you for these things:

    Network Domain. Enter the DNS domain in which your server is or will be registered in. For example, if your server's full DNS name is server.mydomain.net. you would type mydomain.net here.

    Server Name. Your server's full DNS name. From the example above, you would type server.mydomain.net here.

    Administrator's Email Address. Enter the server administrator's or webmaster's email address here. This address will be displayed along with error messages to the client by default.

    For whom to install Apache Select for All Users, on Port 80, as a Service - Recommended if you'd like your new Apache to listen at port 80 for incoming traffic. It will run as a service (that is, Apache will run even if no one is logged in on the server at the moment) Select only for the Current User, on Port 8080, when started Manually if you'd like to install Apache for your personal experimenting or if you already have another WWW server running on port 80.

    The installation type. Select Typical for everything except the source code and libraries for module development. With Custom you can specify what to install. A full install will require about 13 megabytes of free disk space. This does not include the size of your web site(s).

    Where to install. The default path is C:\Program Files\Apache Software Foundation under which a directory called Apache2.2 will be created by default.

    During the installation, Apache will configure the files in the conf subdirectory to reflect the chosen installation directory. However, if any of the configuration files in this directory already exist, they will not be overwritten. Instead, the new copy of the corresponding file will be left with the extension .default. So, for example, if conf\httpd.conf already exists, it will be renamed as conf\httpd.conf.default. After the installation you should manually check to see what new settings are in the .default file, and if necessary, update your existing configuration file.

    Also, if you already have a file called htdocs\index.html. it will not be overwritten (and no index.html.default will be installed either). This means it should be safe to install Apache over an existing installation, although you would have to stop the existing running server before doing the installation, and then start the new one after the installation is finished.

    After installing Apache, you must edit the configuration files in the conf subdirectory as required. These files will be configured during the installation so that Apache is ready to be run from the directory it was installed into, with the documents server from the subdirectory htdocs. There are lots of other options which you should set before you really start using Apache. However, to get started quickly, the files should work as installed.

    Advanced Installation Topics

    One feature of the installer, "Build Headers and Libraries", can be ignored by most users, but should be installed if compiling third party modules. The "APR Iconv Code Pages" can similarly be omitted by most users, unless using mod_charset_lite or a third party module which relies on APR internationalization features.

    There are requests to ship a .zip file from time to time. There is no point in the ASF consuming additional storage, mirroring and bandwidth for this purpose, because the .msi installer allows the installation artifacts to all be unpacked using the msiexec /a network installation option. Using this command against any .msi will result in an exploded tree of all of the individual files and components.

    The installation options above can be customized by users familiar with msiexec.exe options and silent installation. The actual installer sources are available in the httpd/httpd/win32-msi/ tree of the httpd project subversion respository. For reference, some of the more common variables which may be modified are;

    • AgreeToLicense (toggle to "Yes")
    • ALLUSERS (choose between Null and "1")
    • ApplicationUsers (toggle to "OnlyCurrentUser")
    • EXISTING_APACHE_SERVICE_PATH
    • INSTALLDIR (default "ProgramFilesFolder\Apache Software Foundation\Apache2.2\")
    • INSTALLLEVEL (default "100", refer to list below)
    • RESOLVED_WINSOCK2 (toggle to "1")
    • SERVERADMIN
    • SERVERDOMAIN
    • SERVERNAME
    • SERVERPORT (default "80")
    • SERVERSSLPORT (default "443")
    • SERVICEINTERNALNAME (default "Apache2.2", no spaces!)
    • SERVICENAME (default "Apache2.2", include spaces)
    • SetupType (default "Typical")

    The installation level of various features, which may be individually toggled, include;

    • Apache (1, base Apache HTTP Server 2.2 feature)
    • ApacheDocs (11, Apache Documentation)
    • ApacheMonitoring (41, Apache Service Taskbar Icon)
    • ApacheRuntime (1, Apache Runtime)
    • BuildFiles (101, Build Headers and Libraries)
    • Iconv (21, APR Iconv Code Pages)
    • OpensslBin (31, OpenSSL Runtime)
    • SslBin (41, Ssl Binaries)
    Customizing Apache for Windows

    Apache is configured by the files in the conf subdirectory. These are the same files used to configure the Unix version, but there are a few different directives for Apache on Windows. See the directive index for all the available directives.

    The main differences in Apache for Windows are:

    Because Apache for Windows is multithreaded, it does not use a separate process for each request, as Apache can on Unix. Instead there are usually only two Apache processes running: a parent process, and a child which handles the requests. Within the child process each request is handled by a separate thread.

    The process management directives are also different:

    MaxRequestsPerChild. Like the Unix directive, this controls how many requests (actually, connections) which a single child process will serve before exiting. However, unlike on Unix, a replacement process is not instantly available. Use the default MaxRequestsPerChild 0. unless instructed to change the behavior to overcome a memory leak in third party modules or in-process applications.

    Warning: The server configuration file is reread when a new child process is started. If you have modified httpd.conf. the new child may not start or you may receive unexpected results.

    ThreadsPerChild. This directive is new. It tells the server how many threads it should use. This is the maximum number of connections the server can handle at once, so be sure to set this number high enough for your site if you get a lot of hits. The recommended default is ThreadsPerChild 150. but this must be adjusted to reflect the greatest anticipated number of simultaneous connections to accept.

    The directives that accept filenames as arguments must use Windows filenames instead of Unix ones. However, because Apache may interpret backslashes as an "escape character" sequence, you should consistently use forward slashes in path names, not backslashes.

    While filenames are generally case-insensitive on Windows, URLs are still treated internally as case-sensitive before they are mapped to the filesystem. For example, the <Location>. Alias. and ProxyPass directives all use case-sensitive arguments. For this reason, it is particularly important to use the <Directory> directive when attempting to limit access to content in the filesystem, since this directive applies to any content in a directory, regardless of how it is accessed. If you wish to assure that only lowercase is used in URLs, you can use something like:

    RewriteEngine On

    RewriteMap lowercase int:tolower

    RewriteCond % [A-Z]

    RewriteRule (.*) $ [R,L]

    When running, Apache needs write access only to the logs directory and any configured cache directory tree. Due to the issue of case insensitive and short 8.3 format names, Apache must validate all path names given. This means that each directory which Apache evaluates, from the drive root up to the directory leaf, must have read, list and traverse directory permissions. If Apache2.2 is installed at C:\Program Files, then the root directory, Program Files and Apache2.2 must all be visible to Apache.

    Apache for Windows contains the ability to load modules at runtime, without recompiling the server. If Apache is compiled normally, it will install a number of optional modules in the \Apache2.2\modules directory. To activate these or other modules, the new LoadModule directive must be used. For example, to activate the status module, use the following (in addition to the status-activating directives in access.conf ):

    LoadModule status_module modules/mod_status.so

    Information on creating loadable modules is also available.

    Apache can also load ISAPI (Internet Server Application Programming Interface) extensions such as those used by Microsoft IIS and other Windows servers. More information is available. Note that Apache cannot load ISAPI Filters, and ISAPI Handlers with some Microsoft feature extensions will not work.

    When running CGI scripts, the method Apache uses to find the interpreter for the script is configurable using the ScriptInterpreterSource directive.

    Since it is often difficult to manage files with names like .htaccess in Windows, you may find it useful to change the name of this per-directory configuration file using the AccessFilename directive.

    Any errors during Apache startup are logged into the Windows event log when running on Windows NT. This mechanism acts as a backup for those situations where Apache is not yet prepared to use the error.log file. You can review the Windows Application Event Log by using the Event Viewer, e.g. Start - Settings - Control Panel - Administrative Tools - Event Viewer.

    Running Apache as a Service

    You can install Apache as a service automatically during the installation. If you chose to install for all users, the installation will create an Apache service for you. If you specify to install for yourself only, you can manually register Apache as a service after the installation. You have to be a member of the Administrators group for the service installation to succeed.

    Apache comes with a utility called the Apache Service Monitor. With it you can see and manage the state of all installed Apache services on any machine on your network. To be able to manage an Apache service with the monitor, you have to first install the service (either automatically via the installation or manually).

    You can install Apache as a Windows NT service as follows from the command prompt at the Apache bin subdirectory:

    httpd.exe -k install

    If you need to specify the name of the service you want to install, use the following command. You have to do this if you have several different service installations of Apache on your computer. If you specify a name during the install, you have to also specify it during any other -k operation.

    httpd.exe -k install -n "MyServiceName"

    If you need to have specifically named configuration files for different services, you must use this: