Здесь я расскажу как организовать хостинг сайта на своем компьютере. Для примера — сайт под управлением WordPress. В качестве операционной системы будет использоваться Windows Server 2008 R2. (о организации хостинга в Windows 8 можно прочитать здесь). Кто-то начнет сразу кричать о легкости и бесплатности Linux, и я не буду спорить, но мне нравится эта ОС. Она надежная и легкая в администрировании. На мой субъективный взгляд у нее один недостаток — цена. Кроме того, я не утверждаю, что представленная ниже конфигурация сервера для хостинга является самой лучшей и удобной. Я просто опишу последовательность действий, который я предпринял, чтобы мой сайт заработал. Итак:
0. Оглавление
- Что потребуется
- Запуск веб-сервера IIS
- Установка PHP
- Установка MySQL
- Установка WordPress
1. Что потребуется
- Подключенный к сети Интернет, постоянно работающий компьютер, под управлением Windows Server 2008 R2 (О том как установить Windows Server 2008 я писал здесь).
- Выделенный IP-адрес на текущем подключении.
- Зарегистрированное доменное имя (О том как это сделать можно прочитать здесь).
- Доменное имя должно быть привязано к текущему выделенному IP (И об этом я тоже писал здесь)
2. Запуск веб-сервера IIS
Для начала нашему серверу необходимо добавить роль Web-сервера. В Windows Server 2008 эта роль называется Internet Information Services или IIS. Для добавления заходим в «Пуск» — «Администрирование» — «Диспетчер сервера». Раскрываем вкладку «Роли» и нажимаем «Добавить роли» .
Запустится «Мастер добавления ролей», нажимаем «Далее» и в списке выбираем «Веб-сервер (IIS)» .
Нажимаем 2 раза «Далее» и попадаем на страницу выбора служб ролей. Помимо уже отмеченных служб, отмечаем «ASP.NET», «Расширяемость .NET», «CGL», «Расширения ISAPI», «Фильтры ISAPI», нажимаем «Далее» и «Установить» .
После завершения установки в Ролях появилась вкладка «Веб-сервер (IIS)», в которой содержится «Диспетчер служб IIS» (Также он доступен через «Пуск» — «Администрирование» — «Диспетчер служб IIS»)
В диспетчере мы видим наш сервер, и вкладку «сайты», по умолчанию содержащую «Default Web Site». Этот сайт состоит из приветственной страницы IIS. Мы можем просмотреть ее открыв Internet Explorer и в строке адрес введя http://localhost
Можно сразу удалить эту страницу, кликнув в «Диспетчере служб IIS» по ней правой кнопкой и выбрав «Удалить» .
На этом подготовка операционной системы закончена. Далее надо установить PHP и MySQL.
3. Установка PHP
Нам необходимо реализовать поддержку языка PHP. Для этого нужно установить и запустить соответствующую службу. Скачиваем с http://windows.php.net/download/установщик php-сервера. На момент написания статьи актуальной была версия 5.3.6. После скачивания устанавливаем PHP-сервер, следуя инструкциям инсталлятора не меняя настроек и выбрав режим «IISFastCGI» . Более подробно об установки PHP можно прочитать в статье «Установка и настройка компоненты PHP для веб-сервера IIS».
Теперь нужен плагин PHP Manager for IIS для управления PHP из из диспетчера IIS. Скачиваем его здесь: http://phpmanager.codeplex.com/releases/view/69115. После загрузки также устанавливаем его следуя инструкциям инсталятора. Если все сделано правильно в Диспетчере служб IIS должна появиться оснастка «Администратор PHP»
Запускаем ее, и нажимаем на «Зарегистрировать новую версию PHP», указываем путь к исполняемому файлу php и нажимаем «ОК»
Все, на этом регистрация PHP завершена.
4. Установка MySQL
Для хранения базы данных будем использовать бесплатный MySQL. Скачиваем установщик на официальной странице http://www.mysql.com/downloads/installer/. Последняя версия на момент написания статьи 5.5.13. После загрузки запускаем установку, соглашаемся с лицензионным соглашением, выбираем режим «Typical» и нажимаем «Install». После завершения установки, оставляем галочку «Launch the MySQL Instance Configuration Wizard» и нажимаем «Finish».
Запустится вышеназванный мастер. Нажимаем «Next» и выбираем режим «Standart Configuration».
Нажимаем «Next», ничего не меняя еще раз «Next» и вводим пароль на учетную запись «root». Советую сразу записать пароль на листок. Как говорится, тупой карандаш лучше острой памяти. А лучше всего использовать специальные менеджеры паролей. Еще раз жмем «Next» и «Execute». Если все прошло хорошо, то мы должны увидеть следующее:
Жмем «Finish». Установка завершена.
Для управления MySQL я использую простую бесплатную утилиту HeidiSQL, которую можно скачать с http://www.heidisql.com/download.php. На момент написания статьи последней была версия 6.0. Установив программу, следуя инструкциям инсталлятора и запустив ее, мы увидим окно «Session manager», где нужно добавить подключение к нашему MySQL серверу.
Нажимаем «New» и оставляем все поля нетронутыми, введя лишь тот самый пароль, который мы записали на предыдущем шаге.
Жмем «Open» и соглашаемся с сохранением настроек. Теперь нам надо создать новую базу, для нашего сайта. Для этого в окне слева с наименованием баз кликаем правой кнопкой, выбираем «Create new Database».
Заполняем параметры следующим образом:
- Name: Любое имя нашей базы (может совпадать с именем домена)
- Character set: utf8
- Collation: utf8_unicode_ci
и жмем «ОК», после чего наша база должна появиться в списке:
После чего настройка MySQL тоже закончена. Более подробно про установку и настройку MySQL можно прочитать в статье «Установка и настройка MySQL + HeidiSQL».
5. Установка WordPress
Ну вот, можно приступать и к самому сайту. Мой сайт сделан на движке WordPress. На дату статьи последней бала версия 3.1.3. Создадим на диске С папку WEB. С официального сайта http://ru.wordpress.org/ скачиваем архив, который нужно извлечь с созданную папку. В папке WEB появится каталог wordpress, который переименуем в соответствии с нашем доменным именем.
Теперь в корне этого каталога найдем файл «wp-config-sample.php» и откроем его любым текстовым редактором, например блокнотом. Найдем и изменим в нем только следующие параметры:
В строке
- define(‘DB_NAME’, ‘database_name_here’); — вместо database_name_here пишем имя созданной нами базы данных. (В моем случае должно получиться define(‘DB_NAME’, ‘tavalik);
- define(‘DB_USER’, ‘username_here’); — вместо username_here пишем имя пользователя root.
- define(‘DB_PASSWORD’, ‘password_here’); — вместо password_here пишем сохраненный нами пароль.
и сохраняем под именем wp-config.php.
Теперь опять заходим в «Диспетчер служб IIS», находим вкладку «Сайты», кликаем по ней правой кнопкой и выбираем «Добавить веб-сайт»
Вводим имя нашего сайта, указываем физический путь к сайту (в моем примере это C:\WEB\tavalik) и нажимаем «ОК».
После этого открываем Internet Explorer, в строке адреса вводим http://localhost и попадаем на страницу установки WordPress. Вводим заголовок сайта, имя пользователя и пароль для входа на сайт, адрес электронной почты и нажимаем «Установить WordPress».
После сообщения об успешной установке нажимаем на «Войти», вводим только что придуманные логин и пароль и попадаем на консоль управления сайтом. Находим в нижнем левом углу «Параметры» .
Вводим краткое описание сайта, и в поля «Адрес WordPress (URL)»и «Адрес сайта (URL)» вводим имя нашего домена. Нажимаем «Сохранить изменения» и….
Все, наш сайт готов. Можно пользоваться. Для проверки вводим в строке браузера имя сайта и, если все сделано правильно, попадаем на начальную страничку.
Запуск веб-сайта на Windows Web Server 2008 R2 — шаг за шагом
Для тех, кто никогда не разворачивал веб-сайты на Windows Server, процесс может казаться сложным и непонятным. Поэтому, в этой небольшой статье-инструкции, я хочу рассказать о полном процессе установки и настройки — от момента загрузки с установочного диска, до развертывания WordPress. Я покажу, что процесс простой и даже приятный.
Что нам нужно?
- Дистрибутив Windows web Server 2008 R2 (для экспериментов подойдет trial версия, потом ее можно будет активировать используя лицензионный ключ)
- Компьютер с 64-битным процессором (x64), 1 Гб памяти и DVD-приводом
- Выделенный статический IP адрес, предоставленный провайдером Интернет
- Час времени для того, чтобы установить и настроить веб-сервер
Если у нас все это есть, тогда — поехали!
Шаг 1. Загрузка с установочного диска
Устанавливаем в BIOS загрузку с диска, вставляем диск и, после перезагрузки, нажимаем любую клавишу после появления надписи “Press any key to boot from CD”.
Шаг 2. Установка Windows Web Server 2008 R2
Там всего одна кнопка, начинающая установку. Запустить установку сервера – это очень просто!
Перед установкой нужно выбрать версию Windows Web Server 2008 R2. На выбор предлагаются Full и Server Core версии. При выборе Full, будет установлен графический интерфейс, и если вы впервые устанавливаете сервер и не знаете, как управлять им из консольной строки, следует выбрать именно Full версию.
Во время процесса установки будут распакованы и установлены необходимые файлы.
После этого компьютер будет автоматически перезагружен – после перезагрузки следует вытащить компакт-диск из DVD-привода, либо отменить в BIOS загрузку с компакт-диска, чтобы загружалась установленная система.
После перезагрузки установщик Windows Server предложит принять лицензионное соглашение, после чего закончит установку.
После второй перезагрузки система будет полностью установлена и вам останется только настроить веб-сервер, чтобы запустить на нем веб-сайт.
Шаг 3. Настройка веб-сервера
После первой загрузки веб-сервера вы увидите экран с набором ссылок для управления сервером.
Настройка сетевых параметров
Поскольку для сервера нужен выделенный статический IP адрес, получаемый от провайдера, вам, наверное, потребуется настроить сетевые параметры в соответствиями с теми инструкциями, которые вам сообщит провайдер – IP адрес, Gateway, адрес DNS сервера.
Для того чтобы настроить сетевые параметры в основном инструменте управления сервером, о котором сказано выше, щелкнуть ссылку Configure Networking, дальше щелкнуть правой кнопкой мыши по значку активного сетевого соединения и выбрать пункт меню Properties.
Затем выбрать в списке пункт Internet Protocol Version 4 (TCP/IP v4), нажать кнопку Properties.
В открывшемся окне указать все параметры, сообщенные вам провайдером Интернет или администратором локальной сети.
Для того, чтобы запустить веб-сервер, нужно на упомянутом выше экране инструмента управления сервером щелкнуть по ссылке Add roles и в открывшемся окне выбрать Web Server (IIS).
После этого нажать кнопку Next несколько раз, чтобы установить веб-сервер.
После окончания установке веб-сервер будет запущен автоматически и вы сможете посмотреть сайт по умолчанию набрав в окне браузера localhost/, либо IP адрес сервера.
Для того, чтобы управлять веб-сервером в главном меню нужно запустить приложение Internet Information Services (IIS) Manager. Инструкции по использованию Internet Information Services (IIS) Manager можно найти на сайте learn.iis.net и на сайте www.techdays.ru.
С этого момента вы уже можете размещать HTML странички на вашем только что установленном веб-сервере.
Шаг 4. Установка веб-сайта
Просто сервер без динамического сайта, наверное, никому и не нужен. Поэтому неплохой идеей является установка приложений.
Для того, чтобы облегчить этот процесс создан специальный инструмент Web Platform Installer, который можно скачать на сайте microsoft.com/web/.
Откройте сайт microsoft.com/web Поскольку на сервере настроена повышенная система безопасности, будут появляться окна с сообщениями о заблокированных элементах на страницах сайта. Чтобы эти окна не досаждали нужно снять галку Continue to prompt и нажать Close.
После этого в настройках Internet Explorer 8 нужно открыть окно Tools -> Internet Options, выбрать вкладку Security, щелкнуть по значку Trusted Sites, нажать кнопку Sites и в появившемся окне снять галку Require server verification, ввести в поле адрес download.microsoft.com и нажать Add. Закрыть окно и продолжить работать с браузером.
Качаем и запускаем Web Platform Installer.
После запуска Web Platform Installer, сразу же можно приступить к установке популярных веб-приложений. Пусть в этот раз это будет популярный движок блогов WordPress.
Для установки WordPress щелкните по вкладке Web Applications слева, проматайте бегунком список до конца и поставьте галку рядом с названием WordPress.
Смело нажимайте кнопку Install. Вам покажут список компонентов, которые будут установлены и настроены для работы WordPress.
Нажмите I Accept. После этого вас попросят придумать пароль для администратора базы данных MySQL – придумайте и запишите его куда-нибудь, чтобы не забыть, он понадобится при дальнейшей установке.
Установка начнется, будут скачаны и установлены все компоненты, после чего инструмент задаст несколько дополнительных вопросов.
Сначала имя сайта для которого нужно установить веб-приложение. Можно оставить все настройки по умолчанию.
Затем нужно будет сконфигурировать базу данных: указать пароль администратора, который вы придумали на предыдущем шаге и заполнить пустые поля – в основном это ключевые фразы, необходимые для безопасности и пароль пользователя базы данных для настройки веб-сайта – вам эти данные тоже могут понадобиться в будущем, поэтому их лучше куда-нибудь записать.
После всех настроек можно нажать на ссылку Launch WordPress и продолжить ужа настройку самого сайта в браузере.
Нужно придумать название блога и ввести ваш адрес электронной почты, после чего для вас будет сгенерирован пароль, разумеется его нужно куда-то записать – он понадобится для входа на сайт и управления им.
Все, сайт установлен и вы можете с ним работать! Видите, как просто можно настроить сайт. Всего-то несколько минут.
Шаг 5. Привязка доменного имени
Для того, чтобы привязать к вашему сайту доменное имя вроде vasya-pupkin.ru, нужно зарегистрировать это доменное имя, например на сайте nic.ru, после чего настроить DNS сервера регистратора доменного имени так, как указано на сайте регистратора, чтобы эти доменные имена ссылались на IP адрес вашего сервера.
После этого можно привязать доменное имя к сайту. Для этого в инструменте Internet Information Services (IIS) Manager нужно выбрать сайт (по умолчанию там один Default) и щелкнуть на панели справа ссылку Bindings….
В открывшемся окне добавить доменное имя, по которому должен отвечать этот сервер.
After you have learned to work with the many tools in
IIS to manage the environment, you will need to learn how a website is
stored and how to work with the applications your website may need to
support. In this section, you will see a basic understanding on how IIS
can provide support for your websites.
1. Understand the Basics of IIS Websites
Before you can work with
applications, you need to understand the basics of how websites are used
in IIS. Even though your websites may have a combination of simple
static web pages and complex applications, all websites have one thing
in common. The files supporting the website are stored on the server.
Being able to quickly navigate and work with these files provides you
with a quick path to fix, replace, or even troubleshoot your
applications.
Typically, before you start to
work directly with your websites by looking into the directories, you
will normally have a testing process in place. The testing process is
essential so that when you modify the website currently in production,
you do not crash the website or cause your users or even customers any
issues.
By default your websites files are stored on your system drive under the inetpub\wwwroot
directory. When your website programmers want to change the files, they
can quickly navigate directly to the directory and work with the files
on your websites. You can also view the website contents directly in the
IIS Management Console. This is especially useful if the website is on a
Windows Server 2008 R2 Server Core installation. To view the content in
the IIS Management Console, you need to be in the content view.
-
Open IIS Management Console by selecting Start => Administrative Tools => Internet Information Services (IIS) Manager.
-
In the navigation tree, click the server where the website you want to manage is located.
-
In the middle pane toward the bottom of the IIS Management Console window, click Content view.
-
Double-click the site you want to manage, and you will see a screen similar to Figure 1.
Figure 1. Content view in IIS
-
From
the content view window, you can right-click any whitespace in the
console and select Explore. This will take you directly to the Windows
Explorer view of the directory where you can modify and work with your
files.
One of the nice things about
being able to work with your websites directly like this is that it does
not require a lot of administrative burden when you need to move the
application’s files and settings. Even if the application is connected
to a server, at the end of the day you are just moving files and not
changing the configuration of the applications. You still want to test
and verify your applications prior to moving the files.
Moving the location of your
websites from one physical location to another involves two steps. First
you configure the website’s physical directory, and second you copy/cut
and paste the files into the new directory. Moving the physical path
for your websites is the same procedure regardless of the application
you are moving. You could be moving a .NET application or a PHP
application. Keep in mind you are just changing the location of the
files, not the configuration. Changing the physical directory is just a
matter of modifying a setting inside the IIS Management Console:
-
Open IIS Management Console by selecting Start => Administrative Tools => Internet Information Services (IIS) Manager.
-
In the navigation tree, click the server where the website you want to manage is located.
-
Double-click Sites in the middle details pane, and click the site you want to change.
-
In the right Actions pane, click Advanced Settings; you will see a screen similar to Figure 2.
Figure 2. Website advanced settings
-
Click
the physical path parameter, and either type in the new path location
or click the ellipsis button to browse to the new location. -
After you have configured your new directory, click Finish.
-
After
you have changed the configuration in IIS, go to the original file
location for the website, and copy and paste the contents to the new
location.
2. Work with Applications
Most of your websites will
contain some type of dynamic content, most likely generated from an
application on your web server. One of the areas you need to understand
is how IIS works with applications. Specifically, you need to understand
the nature of application pools and how they provide your server
stability.
Application pools allow
you to separate running applications on your web server. Therefore, if
one application crashes on your server, it will not impact any other
applications currently running on your web server. Working with
application pools allows you to configure how applications are run on
your server. However, working with application pools means you need to
understand how the applications need to run on your server. Often times,
you will need to speak to a website developer to make sure you provide
the proper support for the application.
When you create an application
pool, you will need to know a couple of aspects about the application
you are going to support. First, you need to know whether the
application is running using managed code; this typically means the
application requires the .NET Framework to run properly. Second, you
will want to know how the application pipe will be managed so you know
if you should choose either Integrated or Classic. Classic is provided
for backward compatibility for application support and simply means IIS
will not use the IIS integrated pipeline for managed code. Again, take
the time for a quick conversation to help provide adequate support to
your web developers.
2.1. Recycle Applications
One last task you may need to
perform from time to time is recycling your application pool. This will
help free up resources on your web server in case an application
encounters an error. Recycling your application pools periodically will
allow you to maintain your applications and keep them running smoothly.
You can set recycling to occur on regular intervals, or you can recycle
an application pool immediately. When you recycle an application pool,
you essentially clear up system resources and system state information.
This could negatively impact users of your website, so you need to try
to recycle the applications in off-hours. When you recycle an
application pool on your server, all existing session state data will be
lost on your server. If the application you are recycling depends on
the session state data, any users with active connections may encounter
problems when you recycle the application pool. This is why you should
try to make sure you recycle the applications during downtime, if
possible, to minimize the impact on your users.
-
Open IIS Management Console by selecting Start => Administrative Tools => Internet Information Services (IIS) Manager.
-
In the navigation tree, click the + sign next to your server to expand the container.
-
Click Application Pools.
-
Click the application pool you want to recycle.
-
If
you want to recycle the application pool immediately, click Recycle in
the Actions pane on the right. The recycle request will process
immediately. If you want to set regular recycle intervals, click
Recycling in the Actions pane on the right. -
If you clicked Recycling, you will see a screen similar to Figure 3.
Figure 3. Recycling application pools
-
The
recycling conditions will allow you to set a variety of conditions when
you recycle. You can set the time, number of requests, specific time,
or even the memory usage of an application. When you are done selecting
your conditions, click Next. -
You
can also create event log entries when a recycling process has occurred
on your server. The choices you will see here will be based on the
selections you made on the recycling conditions. When you are done
selecting your logging options, click Finish.
3. Integrate PHP Applications in IIS
One of the tasks you may be
asked to perform as a web administrator is to provide support of PHP
applications on your IIS web server. At first you might be inclined to
think that PHP applications are not supported on a Microsoft platform
like IIS. Fortunately, IIS provides full support for working with PHP
applications on the IIS platform. All you need to do from an IT
perspective is to know how the components in IIS provide support for
these applications and how you can maintain them. One of the great
things about this support is that to IIS, whether the application is PHP
or not, it is treated like any other applications. It will have
application pools, and you will be able to support multiple versions of
PHP on the same server.
Before you can begin working
with your PHP applications in IIS, you need to make sure you have
installed the proper IIS component to provide the PHP applications with
the back-end support they will need. In the case of IIS, you will need
to install the CGI component located under the Application Development
section of IIS. This component installs the underlying framework called
FastCGI that provides the necessary support for PHP applications to run
properly on IIS.
3.1. Install CGI on IIS
You can install CGI during
the normal install of IIS or after you have already installed IIS. To
install CGI if you already have installed IIS, you will need to install
the additional role service.
-
Open Server Manager by selecting Start => Administrative Tools => Server Manager.
-
Click the + next to Roles to expand the tree.
-
Right-click Web Server (IIS), and select Add Role Services.
-
Select CGI in the Application Development section, and click Next.
-
Review the confirmation screen and your selections, and when you are ready, click Install.
-
Review the summary screen, correct any error messages, and click Close.
After you have installed
CGI onto your IIS server, you will then need to download the version of
PHP required for your web server. When you go to download the PHP
package, you will see two versions for Windows; one titled thread-safe,
and another is non-thread-safe. You want to download the non-thread-safe
version of PHP for your IIS server on Windows Server 2008 R2. The
built-in FastCGI component will handle the necessary thread process
checks for process integrity normally handled by the thread-safe version
of PHP. This means better performance for the PHP applications loaded
on your server.
Using thread-safe PHP will
typically ensure your applications’ threads run properly, in order, and
safely. Typically this is a very good thing. Even though this may impact
performance, making sure the applications run properly and smoothly is
vital.
Non-thread-safe
applications are going to try to execute the threads process as quickly
as the threads can be called and executed. This sometimes means the
threads bump into other threads or run improperly. The advantage of
non-thread-safe applications is typically performance.
So, this is the age-old
question of performance vs. reliability and is why IIS is so special.
The FastCGI component built in to IIS on Windows Server 2008 R2 will
make sure the threads are executed safely. In a sense, it takes the
place of the thread-safe version of PHP in regard to thread safety. You
can expect the non-thread-safe PHP package to run faster with
reliability on your IIS server.
You also need to make several changes to your PHP.ini file for the applications to run properly. You have to locate and uncomment the following sections in your PHP.ini file:
-
Set fastcgi.impersonate=1.
-
Set cgi.fix_pathinfo=1.
-
Set cgi.force_redirect=0.
-
Set open_basedir to point to a folder or network path where the content of the website is located. By default, on a IIS server, this is c:\inetpub\wwwroot.
-
Set extension_dir
to the location where the PHP extensions reside. If you have installed
PHP with the default settings, you would most likely set this parameter
to extension_dir = «./ext».
Lastly, you need to
set the application association for PHP applications when they are
accessed by your web server. In IIS this is called the handler mappings and is similar to mapping a file extension to a program such as .doc for Microsoft Word. The PHP applications will have the .php
extension. IIS will need to know how to process the files when the
requests come in. With the newer PHP for Windows packages, this handler
mapping is created; however, if it does not exist, you will have to
configure the IIS handler mapping. This will make sure that when it
processes a .php file, it passes the component to the FastCGI component.
-
Open IIS Management Console by selecting Start => Administrative Tools => Internet Information Services (IIS) Manager.
-
Click your server or website in the console tree on the left.
-
Double-click Handler Mappings in the center pane of the IIS console.
-
Look for an option in the Path column with a value of *.php. If one exists, double-click the mapping, and your settings should be similar to Figure 4.
Figure 4. PHP handler mapping in IIS
-
If you do not see a *.php
handler mapping, click Add Module Mapping on the right action list.
Configure the mapping with the following settings, which assumes you
used the default installation settings for PHP:-
Request Path: *.php
-
Module: FastCGI
-
Executable: Location of PHP installation (for example, c:\program files\php\php-cgi.exe)
-
Name: Can be any value you want
-
Любая система на ASP.Net включая KooBoo требует наличие установленного IIS на веб-сервере, где будет работать Ваш сайт.
Предположим, что на Вашем сервере установлена система Windows Web Server 2008 R2.
Чтобы установить на него IIS нам необходимо сначала установить специальную роль для сервера, называемую «роль Web Server«.
В оснастке Sever Manager (которая обычно запускается автоматически при старте системы) выбираем команду «Add Roles«:
На вводном окне нажимаем Next.
Далее в списке выбора ролей выбираем «Web Server» и нажимаем Next.
На вводном окне просто нажимаем Next.
Далее в списке сервисов выбранной роли я рекомендую выбрать следующие параметры:
И тот же список прокрученный ниже:
Нажимаем Next, а затем Install.
Если в дальнейшем будут использоваться приложения на .Net Framework 4, то необходимо зарегистрировать его компоненты на IIS. (подробнее здесь — http://msdn.microsoft.com/ru-ru/library/k6h9cz8h.aspx)
Для этого открываем на сервере консоль командной строки под администратором (cmd.exe) и запускаем из нее программку «aspnet_regiis» с ключом «-i«. Обычно она расположена в директории установленного .Net Framework. Пример пути: C:\Windows\Microsoft.NET\Framework64\v4…
Пример запуска команды регистрации компонентов ASP.Net Framework 4.0 на IIS: aspnet_regiis -i
После выполнения этой команды, зарегистрированные компоненты Вы сможете увидеть в IIS в списке «Handler Mappings«:
© Элла С. (Автор: Ella Sea)
I think it is fitting that my first ever post on this WordPress Blog would be about setting up a WIMP server (Windows Server 2008 R2, IIS, MySQL & PHP).
Being a former Windows Systems Administrator I wanted to keep as many components running on familiar Microsoft applications (IIS 7.5 & SQL Server 2008 R2) and found this article explaining how to do it. However, at the time of writing this article I found that the WordPress on SQL Server (wp-sqlsrv) distribution was unavailable* so the only option was to use MySQL. In retrospect I am very happy with this outcome as the process of learning about MySQL has been very enjoyable and so far has proven to be a very stable and easy-to-use database application .
* Please note that the WordPress on SQL Server (wp-sqlsrv) distribution is now available.
The Environment
- Server: Rackspace Cloud VM running Windows Server 2008 R2
- Web server: IIS 7.5
- Database application: MySQL
This blog you are reading is running off the environment above. So far I have found it to be an excellent blogging platform.
Install IIS 7.5
Logically, the first step is to install the web server application, IIS 7.5. From this point onwards I will simply refer to it as IIS. To do so, perform the folowing steps:
1. Click Start > Run then enter servermanager.msc in the Open dialogue box then click OK to load Server Manager:
2. Once Server Manager has loaded, right-click on Roles and click Add Roles, which initiates the Add Roles Wizard:
3. Click Next in the Before You Begin section:
4. Select Web Server (IIS) on the Select Server Role section and click Next:
5. Select the IIS services to be installed on the Select Role Services page. Keep the defaults but also select the CGI check box under Application Development. This enables both the CGI and FastCGI services which is required to use PHP:
6. Click Next and on the Confirmation page click Install.
7. Once the installation has completed, click Start > Run and then enter inetmgr in the dialogue box then click OK to load Internet Information Services (IIS) Manager. This will fire up IIS Manager and you will see IIS running and configured according to the options you selected earlier:
For more information, this article shows how to install IIS 7.5 with default settings and this article shows how add the CGI feature as described above.
Configure IIS 7.5
We now need to configure IIS in preparation for WordPress:
8. Click Start > Run and enter CMD in the dialogue box and then click OK.
9. At the command prompt enter the following and then hit enter on the keyboard:
This creates the directory where the new WordPress site will be located.
10. Open IIS Manager and click on Sites.
11. Right-click on Sites and then click Add Web Site:
In the Add Web Site dialogue box enter these details:
- Name: WordPress
- Physical path: C:\Websites\Wordpress
- Bindings: All Unassigned. If your server has multiple IP addresses and you want the site to listen on a specific IP address select it from the drop-down box.
- Host name: http://www.yourdomain.name. This should contain the fully-qualified domain name for your blog site.
Once all the sections have been completed click OK. You will now see the WordPress site under the Sites folder.
12. Click on Application Pools and in the middle pane you will see an application pool named WordPress. Right-click on it and select Advanced Settings:
13. Find the setting Enable 32-Bit Applications and click the drop-down box and click True. Click OK to save the settings:
We will leverage the improved security in IIS 7.5 by utilising ApplicationPoolIdentity. More information about this can be found here.
14. Select the WordPress site in the Connections pane and then double-click Authentication:
15. Select Anonymous Authentication and in the Actions pane on the right side click Edit:
16. Then select Application Pool Identity and click OK:
17. Click Start > Run and then enter CMD in the Open dialogue box then click OK to load a command prompt enter the following and hit enter:
icacls "C:\Websites\Wordpress" /grant "IIS APPPOOL\Wordpress":(OI)(CI)(RX,W)
This configures the WordPress application pool to have write permissions to the directory where the new WordPress site is located.
IIS is now configured and ready for PHP to be installed!
Install PHP 5.3.10 for Windows
WordPress uses PHP therefore it is the next component to be installed. We require a ‘Non Thread Safe’ version and facilitate the installation we will use the latest version that comes with an ‘Installer’. At the time of writing, version 5.3.10, has an Installer. To proceed, perform the following:
18. Go to http://windows.php.net/download/. Find version 5.3.10, under VC9 x86 Non Thread Safe, click the Installer version to download it. Click here for a direct download.
19. Once downloaded, run the .msi setup file, click Next at the first screen and accept the EULA (End User License Agreement) and then click Next again.
20. Keep the default installation directory, which is C:\Program Files (x86)\PHP:
21. At the Web Server Setup step select IIS FastCGI:
22. Install the following features also; Script Executable, Register *.php files to open automatically and PEAR Install:
23. Click Next then Install and then click on Finish to complete the setup:
Install PHP Manager 1.2
PHP Manager is a plugin for IIS that allows you to manage and configure PHP settings and installations.
24. Go to http://phpmanager.codeplex.com/ and click on ‘View all downloads’ and download and install the x64 version.
25. Open IIS Manager and in the Connections pane select the server name. In the middle pane you will see all installed features within IIS. Select and open PHP Manager:
26. Under the PHP Setup section select View Recommendations:
27. Select all of the recommendations and hit the OK button:
Install MySQL
At the time of writing, MySQL 5.5.21, is the most recent version available.
28. Go to http://dev.mysql.com/downloads/mysql/ and download the 64-bit MSI Installer and run the setup (mysql-5.5.21-winx64.msi)
29. Accept the EULA and click Next.
30. In the Choose Setup Type section select Typical and click Next:
31. In the Ready To Install MySQL 5.5 section click Install:
32. When the installation completes ensure Launch the MySQL Instance Configuration Wizard is ticked and then click Finish:
33. Select Standard Configuration as the configuration type and then Next:
34. Select Server Machine as the server type and then click Next:
35. In the Windows Options section ensure the settings match the image below:
36. In the security options section check Modify Security Settings, enter the root password of your choice and then click Next:
37. In the configuration section shown below click Execute:
38. Once the process completes click Finish:
Configure MySQL for WordPress
We will now create the database for WordPress within MySQL. We will do this via the command line client.
39. Click Start > All Programs > MySQL > MySQL Server 5.5 > MySQL 5.5 Command Line Client to open a MySQL command prompt:
40. Enter the root password you chose earlier in the MySQL setup and hit enter:
41. To create the WordPressDB database type the following and hit enter:
CREATE DATABASE WordPressDB;
You will receive a confirmation that the command was successful:
Query OK, 1 row affected (0.00 sec)
41. To create the wp_user and grant it access and requisite permissions to the WordPressDB database type the following and hit enter:
GRANT ALL PRIVILEGES ON WordPressDB.* TO "wp_user"@"localhost" IDENTIFIED BY "password";
Please note that the “;” signals the end of the command. To go to a second line just hit Enter without a “;” at the end of a line.
42. Type Exit and hit enter to exit the MySQL command line client.
The confirugration of MySQL is now complete. We should now have the following information available for the WordPress install:
- Database Name: WordPressDB
- Database User: wp_user
- DB User Password: password
Install WordPress
Go to http://wordpress.org/download/ and download the latest version of WordPress (currently 3.3.1) and then folllow these steps:
43. Extract the WordPress files to the location of the WordPress site we created earlier in IIS – C:\Websites\Wordpress.
44. Navigate to C:\Websites\Wordpress and find the file named wp-config-sample.php and open it with Notepad, as per below:
45. Ammend the following fields in wp-config-sample.php with the MySQL database info we created earlier :
- DB_NAME: WordPressDB
- DB_USER: wp_user
- DB_PASSWORD: password
The screen shot below shows the variables that need to be changed. This is telling WordPress which database (WordPressDB) to store the configuration data in MySQL and also the connection information (wp_user and password) to be used:
46. Save the file as wp-config.php
47. Type in the following into your browser to start the WordPress installation script:
http://www.yourdomain.com/wp-admin/install.php
Be sure to replace http://www.yourdomain.com with your domain.
48. You will now see the WordPress welcome screen:
You need to configure the following fields with your own personal information:
- Site Title: My First WordPress Blog
- Username: choose your username (default is admin)
- Password: choose your password
- Your E-mail: email@yourdomain.com
49. Click the Install WordPress button and the setup script will run and you should see the following page soon after:
50. Click Login to go to the Admin Login page then enter your WordPress username and password you created earlier and start blogging!
