Как установить apache на windows 10
Перейти к содержимому

Как установить apache на windows 10

  • автор:


Using Apache HTTP Server on Microsoft Windows

This document explains how to install, configure and run Apache 2.4 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.

This document assumes that you are installing a binary distribution of Apache. If you want to compile Apache yourself (possibly to help with development or tracking down bugs), see Compiling Apache for Microsoft Windows.

  • Operating System Requirements
  • Downloading Apache for Windows
  • Customizing Apache for Windows
  • Running Apache as a Service
  • Running Apache as a Console Application
  • Testing the Installation
  • Configuring Access to Network Resources
  • Windows Tuning

See also

Operating System Requirements

The primary Windows platform for running Apache 2.4 is Windows 2000 or later. Always obtain and install the current service pack to avoid operating system bugs.

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:

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:

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

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:

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.4 is installed at C:\Program Files, then the root directory, Program Files and Apache2.4 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.4\modules directory. To activate these or other modules, the 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 ):

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

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:

httpd.exe -k install -n «MyServiceName» -f «c:\files\my.conf»

If you use the first command without any special parameters except -k install , the service will be called Apache2.4 and the configuration will be assumed to be conf\httpd.conf .

Removing an Apache service is easy. Just use:

httpd.exe -k uninstall

The specific Apache service to be uninstalled can be specified by using:

httpd.exe -k uninstall -n «MyServiceName»

Normal starting, restarting and shutting down of an Apache service is usually done via the Apache Service Monitor, by using commands like NET START Apache2.4 and NET STOP Apache2.4 or via normal Windows service management. Before starting Apache as a service by any means, you should test the service’s configuration file by using:

httpd.exe -n «MyServiceName» -t

You can control an Apache service by its command line switches, too. To start an installed Apache service you’ll use this:

httpd.exe -k start -n «MyServiceName»

To stop an Apache service via the command line switches, use this:

httpd.exe -k stop -n «MyServiceName»

httpd.exe -k shutdown -n «MyServiceName»

You can also restart a running service and force it to reread its configuration file by using:

httpd.exe -k restart -n «MyServiceName»

By default, all Apache services are registered to run as the system user (the LocalSystem account). The LocalSystem account has no privileges to your network via any Windows-secured mechanism, including the file system, named pipes, DCOM, or secure RPC. It has, however, wide privileges locally.

It is recommended that users create a separate account for running Apache service(s). If you have to access network resources via Apache, this is required.

  1. Create a normal domain user account, and be sure to memorize its password.
  2. Grant the newly-created user a privilege of Log on as a service and Act as part of the operating system . On Windows NT 4.0 these privileges are granted via User Manager for Domains, but on Windows 2000 and XP you probably want to use Group Policy for propagating these settings. You can also manually set these via the Local Security Policy MMC snap-in.
  3. Confirm that the created account is a member of the Users group.
  4. Grant the account read and execute (RX) rights to all document and script folders ( htdocs and cgi-bin for example).
  5. Grant the account change (RWXD) rights to the Apache logs directory.
  6. Grant the account read and execute (RX) rights to the httpd.exe binary executable.

If you allow the account to log in as a user and as a service, then you can log on with that account and test that the account has the privileges to execute the scripts, read the web pages, and that you can start Apache in a console window. If this works, and you have followed the steps above, Apache should execute as a service with no problems.

When starting Apache as a service you may encounter an error message from the Windows Service Control Manager. For example, if you try to start Apache by using the Services applet in the Windows Control Panel, you may get the following message:

Could not start the Apache2.4 service on \\COMPUTER
Error 1067; The process terminated unexpectedly.

You will get this generic error if there is any problem with starting the Apache service. In order to see what is really causing the problem you should follow the instructions for Running Apache for Windows from the Command Prompt.

If you are having problems with the service, it is suggested you follow the instructions below to try starting httpd.exe from a console window, and work out the errors before struggling to start it as a service again.

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 Start Menu —> Programs —> Apache HTTP Server 2.4.xx —> Control Apache Server 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:

httpd.exe -k shutdown

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

httpd.exe -k restart

if the server is running as a service.

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 httpd.exe , and read the error message. Then change to the logs folder, and review the error.log file for configuration mistakes. Assuming httpd was installed into C:\Program Files\Apache Software Foundation\Apache2.4\ , you can do the following:

cd «\Program Files\Apache Software Foundation\Apache2.4\bin»

Then wait for Apache to stop, or press Control-C. Then enter the following:

cd ..\logs
more < error.log

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:

-f specifies an absolute or relative path to a particular configuration file:

httpd.exe -f «c:\my server files\anotherconfig.conf»

httpd.exe -f files\anotherconfig.conf

-n specifies the installed Apache service whose configuration file is to be used:

httpd.exe -n «MyServiceName»

In both of these cases, the proper ServerRoot should be set in the configuration file.

If you don’t specify a configuration file with -f or -n , Apache will use the file name compiled into the server, such as conf\httpd.conf . This built-in path is relative to the installation directory. You can verify the compiled file name from a value labelled as SERVER_CONFIG_FILE when invoking Apache with the -V switch, like this:

Apache will then try to determine its ServerRoot by trying the following, in this order:

  1. A ServerRoot directive via the -C command line switch.
  2. The -d switch on the command line.
  3. Current working directory.
  4. A registry entry which was created if you did a binary installation.
  5. The server root compiled into the server. This is /apache by default, you can verify it by using httpd.exe -V and looking for a value labelled as HTTPD_ROOT .

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.

The value of this key is the ServerRoot directory which contains the conf subdirectory. When Apache starts it reads the httpd.conf file from that directory. If this file contains a ServerRoot directive which contains a different directory from the one obtained from the registry key above, Apache will forget the registry key and use the directory from the configuration file. If you copy the Apache directory or configuration files to a new location it is vital that you update the ServerRoot directive in the httpd.conf file to reflect the new location.

Testing the Installation

After starting Apache (either in a console window or as a service) it will be listening on port 80 (unless you changed the Listen directive in the configuration files or installed Apache only for the current user). To connect to the server and access the default page, launch a browser and enter this URL:

Apache should respond with a welcome page and you should see «It Works!». If nothing happens or you get an error, look in the error.log file in the logs subdirectory. If your host is not connected to the net, or if you have serious problems with your DNS (Domain Name Service) configuration, you may have to use this URL:

If you happen to be running Apache on an alternate port, you need to explicitly put that in the URL:

Once your basic installation is working, you should configure it properly by editing the files in the conf subdirectory. Again, if you change the configuration of the Windows NT service for Apache, first attempt to start it from the command line to make sure that the service starts with no errors.

Because Apache cannot share the same port with another TCP/IP application, you may need to stop, uninstall or reconfigure certain other services before running Apache. These conflicting services include other WWW servers, some firewall implementations, and even some client applications (such as Skype) which will use port 80 to attempt to bypass firewall issues.

Configuring Access to Network Resources

Access to files over the network can be specified using two mechanisms provided by Windows:

Mapped drive letters e.g., Alias «/images/» «Z:/» UNC paths e.g., Alias «/images/» «//imagehost/www/images/»

Mapped drive letters allow the administrator to maintain the mapping to a specific machine and path outside of the Apache httpd configuration. However, these mappings are associated only with interactive sessions and are not directly available to Apache httpd when it is started as a service. Use only UNC paths for network resources in httpd.conf so that the resources can be accessed consistently regardless of how Apache httpd is started. (Arcane and error prone procedures may work around the restriction on mapped drive letters, but this is not recommended.)

Example DocumentRoot with UNC path

Example DocumentRoot with IP address in UNC path

Example Alias and corresponding Directory with UNC path

When running Apache httpd as a service, you must create a separate account in order to access network resources, as described above.

Windows Tuning

If more than a few dozen piped loggers are used on an operating system instance, scaling up the «desktop heap» is often necessary. For more detailed information, refer to the piped logging documentation.


Copyright 2023 The Apache Software Foundation.
Licensed under the Apache License, Version 2.0.

How to install web server on Windows 10 (Apache 2.4, PHP 8, MySQL 8.0 and phpMyAdmin)

1. Downloading Apache, PHP, MySQL, phpMyAdmin

  • Download Apache for Windows: https://www.apachelounge.com/download/
  • Download PHP 8 for Windows (select ‘Thread Safe’): https://windows.php.net/download/
  • Download MySQL for Windows (select ZIP Archive): http://dev.mysql.com/downloads/mysql/
  • Download phpMyAdmin: https://www.phpmyadmin.net/
  • Download the latest Visual C++ Redistributable for Visual Studio 2015-2022: (direct link to download the 64-bit version, a direct link to the download of the 32-bit version).

Now we have files:

  • httpd-2.4.29-Win64-VC15.zip
  • php-7.2.0-Win32-VC15-x64.zip
  • mysql-8.0.11-winx64.zip
  • phpMyAdmin-4.7.7-all-languages.zip
  • vc_redist.x64.exe

Run and install the vc_redist.x64.exe file, we will not return to it.

2. Create necessary folders

On the drive C create a directory Server; inside it create the bin directory (we will install Apache, PHP, and MySQL there) and data directory (our websites and databases will be located there).

We continue our preparations. In the data directory create two folders:

  • DB (database will be stored here)
  • htdocs (websites will be stored here)

Tree of the important folders that are mentioned in this manual:

3. Installation and configuration Apache 2.4 on Windows

Unpack the Apache files (archive httpd-2.4.25-win64-VC14.zip) to the C:\Server\bin\ directory (we are interested only in the Apache24 folder):

After unpacking, go to the c:\Server\bin\Apache24\conf\ folder and open the httpd.conf file with any text editor.

Save and close the file. Apache configuration is complete!

Open a command prompt (it can be done by simultaneously pressing Win + X). Select ‘Windows PowerShell (admin)’:

and press Enter.

If you see Firewall prompt, select ‘Allow access’.

Also copy-paste and run:

Afterwards in your bowser follow the link http://localhost/ you’ll see something like that

  • Apache works
  • directory c:\Server\data\htdocs\ is empty

You can play with your new shiny web-server: add html-files to the folder, your server is running.

4. Installation and configuration MySQL 8.0 on Windows

In the c:\Server\bin\ folder unpack MySQL archive (the mysql-8.0.11-winx64.zip file). Rename it to mysql-8.0 (just for short).

Go inside the mysql-8.0 folder and create my.ini file. Open this file with any text editor. Copy-paste the following lines:

Save and close it.

Configuration is completed! But we have to initialize and install MySQL 8.0 on Windows. Open Command Prompt (as Admin) and run:

Once the process completed, inside the C:\Server\data\DB\data\ folder automatically generated files should appear:

From now MySQL service will start automatically with every Windows boot.

If initialization failed and there is lack of files in the C:\Server\data\DB\data\ folder and MySQL service failed to start, or in the C:\Server\data\DB\data\*.err file you got errors like that:

To cope the issue, remove all files from C:\Server\data\DB\data\ folder, and to the my.ini file add the line:

After that initialize MySQL again:

Everyone who has issues with MySQL service, to fix it try to reset MySQL installatoin and install in from scratch:

1. Remove the service:

2. In the c:/Server/data/DB/data/ folder remove all files

3. Initialize and install the service:

If the problem persists please provide the content of the C:\Server\data\DB\data\*.err file.

5. Installation PHP 8 on Windows

In the c:\Server\bin\ create new PHP folder and copy there the contents of php-7.1.1RC1-Win32-VC14-x64.zip.

Again open the c:\Server\bin\Apache24\conf\httpd.conf file and append it with lines:


And restart Apache:

In the c:\Server\data\htdocs\ folder create i.php file and copy to there:

In a browser open the http://localhost/i.php address. If you see something like this, it means PHP works:

6. Configuration PHP 8

In the c:\Server\bin\PHP\ folder rename php.ini-development file to php.ini. Open it with a text editor. Find the string

and replace it with

Now find the group of strings:

and replace it with

Now uncomment this group of strings:

They should look like:

Save the file and restart Apache.

7. Installation and configuration phpMyAdmin on Windows

To the c:\Server\data\htdocs\ folder copy the content of phpMyAdmin- Rename phpMyAdmin- to phpmyadmin (for brevity).

In the c:\Server\data\htdocs\phpmyadmin\ folder create config.inc.php file and copy there:

Enter root as name, do not fill password. If everything is fine it should look like that:

8. Usage and backup web-server

In the c:\Server\data\htdocs\ folder put your local web sites, create HTML, PHP and another files. For instance, I created c:\Server\data\htdocs\test\ajax.php file, so this file will be available at the address http://localhost/test/ajax.php and so on.

To create full backup including all web sites and databases, just copy data folder in a save place. If you will need restore your information, with backup you can do it easily.

Before updating web-server modules, backup bin folder, if you will have issues you can fallback to previous versions.

Make backup of the following files, with them you can deploy new instance of the server faster.

  • c:\Server\bin\Apache24\conf\httpd.conf
  • c:\Server\bin\mysql-8.0\my.ini
  • c:\Server\bin\PHP\php.ini
  • c:\Server\data\htdocs\phpmyadmin\config.inc.php

These files keep all settings and when we are installing new web server instance most of the time we are engaged in their editing

9. Extra PHP configuration

Some PHP settings you should know:

It is not necessary to do something with them, but if you are rested into the limits, they will be useful

10. Extra phpMyAdmin configuration

If in phpMyAdmin you see error message:

'Create a database named 'phpmyadmin' and setup the phpMyAdmin configuration storage there'.

It means you fixed the problem.

11. Setting up the mail plug

In the C:\Server\bin\ folder, create one more folder named Sendmail. Now in this new folder create a file sendmail.php and copy-paste the following content:

Open the C:\Server\bin\PHP\php.ini file and append the string:

Save the file and restart your web-server. From this moment every sent letter will be saved in C:\Server\bin\Sendmail\emails\

12. How to add PHP folder to System PATH in Windows

You should add PHP folder to System PATH, otherwise you will have errors every time you start Apache:

To avoid that, add PHP folder to System PATH. Push the Start (‘Win’) button, start typing ‘Edit the system environment variables’ and open the setting window.

Click the ‘Environment Variables’ button:

In the window ‘System variables’ click on ‘Path’ and later on ‘Edit…

Click on ‘New’ and type ‘C:\Server\bin\PHP\’:

Lift the record to the very top:

Save changes and close all windows. Restart the server.

13. Configuring cURL in the Apache web server on Windows

If you do not know what cURL is, then you do not need it. So feel free to skip this step.

cURL is a console utility that allows you to exchange data with remote servers using a very large number of protocols. cURL can use cookies and supports authentication. If a web application requires cURL, then this must be specified in the dependencies. For many popular applications, cURL is not required, for example, for phpMyAdmin and WordPress therefore there is no need to configure cURL.

If cURL is not configured correctly, you will get errors:

To make cURL works in Apache on Windows, you need:

1) Be sure to add the PHP directory to PATH (system environment variables). How to do this said just above: https://miloserdov.org/?p=55#12.

2) In the C:\Server\bin\PHP\php.ini file the extension=curl line should be uncommented.

3) Download the https://curl.haxx.se/ca/cacert.pem file, then in the C:\Server\ folder create a new folder named certs and move the downloaded file to this new folder (C:\Server\certs\).

4) In the C:\Server\bin\PHP\php.ini file find the sting

And replace it with

5) Restart your web-server.

14. Fixing the Asynchronous AcceptEx failed error

When you have hangs, slow traffic and/or when having in your log entries like Asynchronous AcceptEx failed.

You can try the following settings:

15. How to protect the Apache web server from hacking in Windows

How to delete web-server Apache from Windows

If you no longer need a web-server installed with this guide, follow the steps below to uninstall it.

Attention: all the web-sites and their databases created on your local web-server will be deleted!

Как установить веб-сервер Apache с PHP, MySQL и phpMyAdmin на Windows

Веб-сервер — это программа, которая предназначена для обработки запросов к сайтам и отправки пользователям страниц веб-сайтов. Самый популярный пример веб-сервера это Apache.

PHP — это язык программирования. Также называется среда для выполнения скриптов, написанных на PHP. В операционной системе, в том числе и Windows, PHP может быть установлен самостоятельно, без веб-сервера. В этом случае программы (скрипты) на PHP можно запускать из командной строки. Но веб-приложения очень часто используют PHP, данный интерпретатор стал, фактически, стандартом веб-серверов и поэтому они почти всегда устанавливаются вместе.

MySQL — это система управления базами данных (СУБД). Это также самостоятельная программа, она используется для хранения данных, поиска по базам данных, для изменения и удаления данных. Веб-приложения нуждаются в постоянном хранилище, поэтому для веб-сервера дополнительно устанавливается и СУБД. Кстати, вполне возможно, что вы слышали про MariaDB — это тоже СУБД. Первой появилась MySQL, а затем от неё ответвилась MariaDB. Для веб-приложений обе эти СУБД являются взаимозаменяемыми, то есть никакой разницы нет. В этой инструкции я буду показывать установку на примере MySQL, тем не менее если вы хотите попробовать новую MariaDB, то смотрите статью «Инструкция по установке веб-сервера Apache c PHP, MariaDB и phpMyAdmin в Windows».

Что касается phpMyAdmin, то это просто скрипт на PHP, который предназначен для работы с базами данных — наглядно выводит их содержимое, позволяет выполнять в графическом интерфейсе такие задачи как создавать базы данных, создавать таблицы, добавлять, изменять и удалять информацию и т. д. По этой причине phpMyAdmin довольно популярен, хотя и не является обязательной частью веб-сервера.

Особенность Apache и других компонентов веб-сервера в том, что их корни уходят в Linux. И эти программы применяют в своей работе основные концепции этой операционной системы. Например, программы очень гибки в настройке — можно выполнить установку в любую папку, сайты также можно разместить в любой папке, в том числе на другом диске, не на том, где установлен сам веб-сервер. Даже файлы журналов можно вынести на третий диск и так далее. У веб-сервера много встроенных модулей — можно включить или отключить их в любом сочетании, можно подключить внешние модули. Можно создать много сайтов на одном веб-сервере и для каждого из них установить персональные настройки. Но эта гибкая настройка выполняется через текстовые файлы — именно такой подход (без графического интерфейса) позволяет описать любые конфигурации

Не нужно этого боятся — я расскажу, какие файлы нужно редактировать и что именно в них писать.

Мы не будем делать какие-то комплексные настройки — наша цель, просто установить веб-сервер на Windows. Тем не менее было бы странно совсем не использовать такую мощь в настройке. Мы разделим сервер на две директории: в первой будут исполнимые файлы, а во второй — данные (файлы сайтов и баз данных). В будущем, когда возникнет необходимость делать резервные копии информации или обновлять веб-сервер, вы поймёте, насколько удобен этот подход!

Мы установим сервер в отдельную директорию. Для этого в корне диска C:\ создайте каталог Server. В этом каталоге создайте 2 подкаталога: bin (для исполнимых файлов) и data (для сайтов и баз данных).

Перейдите в каталог data и там создайте подпапки DB (для баз данных) и htdocs (для сайтов).

Перейдите в каталог C:\Server\data\DB\ и создайте там пустую папку data.

Для работы всех компонентов веб-сервера необходим файл «Visual C++ Redistributable for Visual Studio 2015-2022» — это официальный файл от Microsoft. Чтобы его скачать перейдите по ссылке. После скачивания, запустите этот файл и выполните установку.

Подготовительные действия закончены, переходим к установке компонентов веб-сервера.

Как установить Apache на Windows

Перейдите на сайт apachelounge.com/download и скачайте .zip архив с веб-сервером:

Распакуйте папку Apache24 из этого архива в C:\Server\bin\.

Перейдите в каталог C:\Server\bin\Apache24\conf\ и откройте файл httpd.conf любым текстовым редактором.

В нём нам нужно заменить ряд строк.

Сохраняем и закрываем файл. Всё, настройка Apache завершена! Описание каждой изменённой директивы вы найдёте на этой странице.

Откройте командную строку (это можно сделать нажав одновременно клавиши Win+x).

Выберите там Windows PowerShell (администратор) и скопируйте туда:

Если поступит запрос от файервола в отношение Apache, то нажмите Разрешить доступ.

Теперь вводим в командную строку:

И нажмите Enter.

Теперь в браузере набираем http://localhost/ и видим следующее:

Это означает, что веб-сервер работает. Чтобы увидеть там файлы, добавьте их в каталог c:\Server\data\htdocs\ — это главная папка для данных сервера, где будут размещаться все сайты.

Как установить PHP на Windows

PHP 8 скачайте со страницы windows.php.net/download/. Выберите версию Thread Safe, обратите внимание на битность. Если вы затрудняетесь, какой именно файл скачать, то посмотрите эту заметку.

В папке c:\Server\bin\ создаём каталог PHP и копируем в него содержимое только что скаченного архива.

В файле c:\Server\bin\Apache24\conf\httpd.conf в самый конец добавляем строчки:

И перезапускаем Apache:

В каталоге c:\Server\data\htdocs\ создаём файл с названием i.php, копируем в этот файл:

В браузере откройте ссылку http://localhost/i.php. Если вы видите что-то похожее, значит PHP работает:

Настройка PHP 8

Настройка PHP происходит в файле php.ini. В zip-архивах, предназначенных для ручной установки и для обновлений, php.ini нет (это сделано специально, чтобы при обновлении случайно не удалить ваш файл с настройками). Зато есть два других, которые называются php.ini-development и php.ini-production. Любой из них, при ручной установке, можно переименовать в php.ini и настраивать дальше. На локалхосте мы будем использовать php.ini-development.

Открываем файл php.ini любым текстовым редактором, ищем строчку

и заменяем её на

Теперь найдите группу строк:

и замените её на:

теперь раскомментируйте эту группу строк:

Этими действиями мы включили расширения. Они могут понадобиться в разных ситуациях для разных скриптов. Сохраняем файл и перезапускаем Apache.

Материалы по дополнительной настройке, в том числе подключение поддержки PERL, Ruby, Python в Apache (только для тех, кому это нужно):

  • Как тестировать отправку писем в PHP на Windows
  • Настройка веб-сервера Apache для запуска программ Ruby на Windows
  • Настройка веб-сервера Apache для запуска программ Perl на Windows
  • Как настроить веб-сервер Apache на запуск Python в Windows

Как установить MySQL в Windows

Бесплатная версия MySQL называется MySQL Community Server. Её можно скачать на странице https://dev.mysql.com/downloads/mysql/. На этой же странице есть установщик в виде исполнимого файла, но я рекомендую скачать ZIP-архив.

На странице скачивания нам предлагают зарегистрироваться или войти в существующую учётную запись — но это делать необязательно. Достаточно нажать на ссылку «No thanks, just start my download».

В каталог c:\Server\bin\ распаковываем файлы из только что скаченного архива. Распакованная папка будет называться примерно mysql-8.0.17-winx64 (зависит от версии), переименуйте её в mysql-8.0.

Заходим в эту папку и создаём там файл my.ini. Теперь открываем этот файл любым текстовым редактором и добавьте туда следующие строки:

Сохраните и закройте его.

Настройка завершена, но нужно ещё выполнить инициализацию и установку, для этого открываем командную строку от имени администратора и последовательно вводим туда:

По окончанию этого процесса в каталоге C:\Server\data\DB\data\ должны появиться автоматически сгенерированные файлы.

Теперь служба MySQL будет запускаться при каждом запуске Windows.

Как установить phpMyAdmin в Windows

Сайт для скачивания phpMyAdmin: phpmyadmin.net.

Прямая ссылка на самую последнюю версию: phpMyAdmin-latest-all-languages.zip.

В каталог c:\Server\data\htdocs\ копируем содержимое только что скаченного архива. Переименовываем эту папку в phpmyadmin.

В каталоге c:\Server\data\htdocs\phpmyadmin\ создаём файл config.inc.php и копируем туда:

В качестве имя пользователя вводим root. Поле пароля оставляем пустым.


Вот и всё — теперь у вас есть свой персональный локальный веб-сервер на своём домашнем компьютере.

Если вдруг у вас что-то не получилось, то скорее всего вы пропустили какой-то шаг или сделали его неправильно — попробуйте всё сделать в точности по инструкции. Если проблема осталась, то ознакомьтесь со справочным материалом «Ошибки при настройке и установке Apache, PHP, MySQL/MariaDB, phpMyAdmin» и если даже он не помог, то напишите о своей ошибке в комментарии.

Большое количество материалов по Apache на русском языке специально для Windows вы найдёте на этой странице.


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

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