Welcome

How to Install a LAMP Stack on Arch Linux

Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.

A LAMP (Linux, Apache, MySQL, PHP) stack is a common web stack used to prepare servers for hosting web content. This guide shows you how to install a LAMP stack an Arch Linux server.

Since Arch does not come in specific versions, this guide is up-to-date as of the December 2015 Arch update.

This guide is written for a non-root user. Commands that require elevated privileges are prefixed with sudo . If you’re not familiar with the sudo command, you can check our Users and Groups guide.

Before You Begin

Apache

Install and Configure

Before changing any configuration files, it is advised that you make a backup of the file. To make a backup: cp /etc/httpd/conf/extra/httpd-mpm.conf ~/httpd-mpm.conf.backup

sudo systemctl enable httpd.service 

Add Name-Based Virtual Hosts

Virtual hosting can be configured so that multiple domains (or subdomains) can be hosted on the server. These websites can be controlled by different users, or by a single user, as you prefer. There are different ways to set up virtual hosts; however, we recommend the method below.

    Open httpd.conf and edit the line DocumentRoot /srv/http to define the default document root:

ErrorLog and CustomLog entries are suggested for more fine-grained logging, but are not required. If they are defined (as shown above), the logs directories must be created before you restart Apache.

sudo mkdir -p /srv/http/default sudo mkdir -p /srv/http/example.com/public_html sudo mkdir -p /srv/http/example.com/logs 
sudo systemctl start httpd.service 

You should now be able to access your website. If no files are uploaded you will see an Index of / page.

Читайте также:  Before linux after linux

Should any additional changes be made to a configuration file restart Apache: sudo systemctl restart httpd.service

MariaDB

Install and Configure

By default, Arch Linux provides MariaDB as a relational database solution. MariaDB is an open source drop-in replacement for MySQL, and all system commands that reference mysql are compatible with it.

    Install the mariadb , mariadb-clients and libmariadbclient packages:

sudo pacman -Syu mariadb mariadb-clients libmariadbclient 
sudo mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql 
sudo systemctl start mysqld.service sudo systemctl enable mysqld.service 
mysql_secure_installation 

Create a Database

CREATE DATABASE webdata; GRANT ALL ON webdata.* TO 'webuser' IDENTIFIED BY 'password'; 

With Apache and MariaDB installed, you are now ready to move on to installing PHP to provide scripting support for your web application.

PHP

PHP makes it possible to produce dynamic and interactive pages using your own scripts and popular web development frameworks. Many popular web applications like WordPress are written in PHP. If you want to develop your websites using PHP, you must first install it.

sudo pacman -Syu php php-apache 

Ensure that all lines noted above are uncommented. A commented line begins with a semicolon (;).

sudo mkdir /var/log/php sudo chown http /var/log/php 
sudo systemctl restart httpd.service 

More Information

You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.

This page was originally published on Monday, October 7, 2013.

Read other comments or post your own below. Comments must be respectful, constructive, and relevant to the topic of the guide. Do not post external links or advertisements. Before posting, consider if your comment would be better addressed by contacting our Support team or asking on our Community Site.

The Disqus commenting system for Linode Docs requires the acceptance of Functional Cookies, which allow us to analyze site usage so we can measure and improve performance. To view and create comments for this article, please update your Cookie Preferences on this website and refresh this web page. Please note: You must have JavaScript enabled in your browser.

Источник

Установка LAMP stack (Linux, Apache, MySQL, PHP) в Arch Linux

LAMP stack – это группа открытых программ для создания и запуска веб-серверов. Данный акроним расшифровывается как Linux, Apache, MySQL, PHP. Для установки программного обеспечения Arch Linux использует мощный менеджер пакетов Pacman, который позволяет загрузить последние версии необходимых пакетов для каждой программы с помощью одной команды.

Читайте также:  Установка линукс разбить диск

Требования

Для того, чтобы следовать данному руководству, необходимы привилегии root (за справкой можно обратиться к статье «Начальная настройка сервера Arch Linux»).

1: Установка Apache

Apache – это свободное открытое программное обеспечение, обеспечивающее работу 50% веб-серверов в мире.

Перед установкой любой программы LAMP необходимо обновлять менеджер пакетов.

Завершив обновление, можно приступать к установке Apache:

Установив Apache, нужно внести пару изменений в настройки.

Откройте конфигурационный файл Apache:

sudo nano /etc/httpd/conf/httpd.conf

Раскомментируйте unique_id_module (для быстрого поиска используйте ctrl w):

#LoadModule unique_id_module modules/mod_unique_id.so

sudo systemctl restart httpd

При перезапуске Apache может появиться следующее сообщение:

httpd: apr_sockaddr_info_get() failed for droplet1
httpd: Could not reliably determine the server’s fully qualified domain name, using 127.0.0.1 for ServerName
[DONE]

Хотя это предупреждение не помешает запуску Apache, его можно легко устранить, внеся в конфигурации имя хоста.

Добавьте имя хоста в конец строки, которая начинается с 127.0.0.1:

127.0.0.1 localhost.localdomain localhost droplet1

В дальнейшем при перезагрузке Apache больше не будет отображать это сообщение.

Веб-сервер Apache установлен! Направьте браузер на IP-адрес сервера (http://11.22.33.444), это откроет каталог авто-индекса. Теперь можно быстро создать пробную страницу, добавив файл index.html в root-каталог Arch, расположенный в srv/http:

sudo nano /srv/http/index.html

Hello, Welcome to Arch


Теперь можно посетить страницу местозаполнителя, перейдя на IP-адрес сервера в браузере.

Как узнать ​​IP-адрес сервера

Запустите следующую команду, чтобы узнать IP-адрес сервера.

2: Установка MySQL

MySQL – это мощная система управления базами данных (СУБД), которая используется для организации и поиска информации.

Примечание: с марта 2013 года MariaDB стала реализацией MySQL в репозиториях Arch. При установке пакет MySQL автоматически заменяется пакетом MariaDB.

Чтобы установить MySQL, откройте терминал и введите данную команду:

При появлении каких-либо извещений или вопросов просто нажмите enter (чтобы принять настройки по умолчанию).

По завершении установки запустите MySQL.

sudo systemctl start mysqld

В завершение нужно запустить настроечный скрипт MySQL.

На данном этапе программа спросит текущий root-пароль MySQL (не путать с root-паролем сервера). Поскольку он еще не установлен, просто нажмите клавишу enter.

Читайте также:  Ralink rt5370 linux drivers

При запросе «Set root password?» введите Y, а затем наберите новый root-пароль MySQL.

После этого проще всего ответить Yes на все появившиеся вопросы. В завершение MySQL перезагрузится и активирует все изменения.

By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL without having to have a user account created for
them. This is intended only for testing, and to make the installation
go a bit smoother. You should remove them before moving into a
production environment.
Remove anonymous users? [Y/n] y
. Success!
Normally, root should only be allowed to connect from ‘localhost’. This
ensures that someone cannot guess at the root password from the network.
Disallow root login remotely? [Y/n] y
. Success!
By default, MySQL comes with a database named ‘test’ that anyone can
access. This is also intended only for testing, and should be removed
before moving into a production environment.
Remove test database and access to it? [Y/n] y
— Dropping test database.
. Success!
— Removing privileges on test database.
. Success!
Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.
Reload privilege tables now? [Y/n] y
. Success!
Cleaning up.

Готово! После инсталляции MySQL осталось только установить PHP.

3: Установка PHP

PHP – это скриптовый язык с открытым исходным кодом, который широко используется для создания динамических веб-страниц.

Для установки PHP нужно открыть терминал и набрать команду:

sudo pacman -S php php-apache

Кроме того, PHP нужно также внести в настройки apache:

sudo nano /etc/httpd/conf/httpd.conf

Внесите в конфигурационный файл следующий блок кода:

# Use for PHP 5.x:
LoadModule php5_module modules/libphp5.so
AddHandler php5-script php
Include conf/extra/php5_module.conf

4: Тестирование установки LAMP stack

Завершив установку всех компонентов LAMP stack, можно проверить работу ПО и просмотреть данные PHP, создав быструю страницу php info.

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

Затем перезапустите apache, чтобы активировать изменения.

sudo systemctl restart httpd

Посетите страницу php info, введя http://11.22.33.444/info.php (и заменив пример ip-адреса настоящим).

Чтобы закрыть установку LAMP, откройте конфигурационный файл Arch по имени innitscripts и внесите Apache и MySQL в список программ, автоматически запускаемых при старте сервера:

sudo systemctl enable mysqld httpd

Готово! Группа программ LAMP установлена на сервер и готова к работе.

Источник

Оцените статью
Adblock
detector