Ubuntu rocks!

Базовая установка и настройка веб-сервера

Решил оформить наконец своё HOW-TO на форуме в нашей вики, т.к. это правильнее и форматирование здесь удобнее. Я постарался изложить материал кратко, намеренно упустив подробности, которые не относятся напрямую к сути (вроде того, что конфиги сервера нужно править от рута). Считаем, что читатель имеет базовый уровень работы с линукс-системами.

Просьба к редакторам тоже там отписываться

Базовая установка и настройка веб-сервера

Установка

apt-get install lamp-server^ phpmyadmin

phpmyadmin — веб-интерфейс для управления БД MySQL.

Иногда при копипасте кода установки может вылезать ошибка, что какой-то пакет не найден. На самом деле все правильно, просто глюк копипаста. Решение вбить руками команду или попробовать стереть название проблемного пакета вместе с пробелами по краям и вбить руками только его.

Настройка Apache

Персональные настройки

FIXME

Начиная с версии Ubuntu Saucy (13.10) свои настройки следует писать в /etc/apache2/conf-available, активировать настройки следует с помощью команды a2enconf.

Свои настройки следует писать в /etc/apache2/conf.d, т.е. создать там файл, например, myconf.conf и определить в нём свои настройки.

## Файл персональных настроек веб-сервера Apache ## Чтобы устранить предупреждение при перезапуске Apache (хотя в целом на производительности это не отразится) ServerName localhost ## Для того, чтобы Apache интерпретировал php и не предлагал сохранить php-файл AddType application/x-httpd-php .php .phtml ## Установка кодировки UTF-8 по умолчанию AddDefaultCharset UTF-8

Для того, чтобы так же работали файлы php, которые начинаются с «» вместо «» нужно, чтобы в /etc/php5/apache2/php.ini было short_open_tag = On

Настройка виртуальных хостов

Есть несколько способов, я же расскажу о том как повесить несколько виртуальных хостов на один IP c доступом к ним по имени сервера.

127.0.0.1 host2.server1 host1.server1

и создаём там файлы, названиями которых будут названия, создаваемых серверов, например host1.server1.conf и host2.server1.conf в эти файлы пишем (здесь показано простейшее, подробнее можно заценить в файле default):

 ServerName host1.server1 DocumentRoot /var/www/host1.server1 AllowOverride All 
 ServerName host2.server1 DocumentRoot /var/www/host2.server1 AllowOverride All 

Далее создаём симлинки на эти файлы в директории /etc/apache2/sites-enabled с помощью команды a2ensite:

a2ensite host1.server1 host2.server1
http://host1.server1 http://host2.server1

Твики и трюки

Этот раздел применять не обязательно, у вас уже всё работает после 1-го раздела. Однако вы можете найти здесь что-то полезное. Я рекомендую не обделить вниманием ускорение (opcode cacher)

Читайте также:  Check machine hardware linux

Ускоряем сервер (Opcode Cacher)

Акселератор PHP — программа, ускоряющая исполнение сценариев PHP интерпретатором путём кэширования их байткода.

Начиная с версии PHP 5.5 в интерпретатор по умолчанию включён Zend OPcache. В этой связи, а также потому что данная статья описывает базовую настройку, из неё убраны описания установки php-apc и php-xcache

Выключаем автозапуск apache2 и mysql

ВАМ ЭТО ДЕЙСТВИТЕЛЬНО НУЖНО? Эти демоны стартуют в родной для себя среде в разы быстрее чем денвер в винде, думаю от 1 сек к времени загрузки ОС и 10 мб ОЗУ вам хуже не станет, а лишних телодвижений не будет…

Выключаем автозапуск Apache:

sudo update-rc.d -f apache2 remove

Выключаем автозапуск MySQL:

sudo nano /etc/init/mysql.conf
start on (net-device-up and local-filesystems and runlevel [2345])
#start on (net-device-up # and local-filesystems # and runlevel [2345])

Разрешаем подключение к MySQL из Мира

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

/etc/mysql/my.cnf

# # Instead of skip-networking the default is now to listen only on # localhost which is more compatible and is not less secure. bind-address = 127.0.0.1

Самое простое — просто закомментировать эту строку.

Кроме этого требуется добавить пользователя, который с разных мест и из разных программ может соединяться с базой, например «admin»:

GRANT ALL PRIVILEGES ON *.* TO admin@"%" IDENTIFIED BY 'my_admin_password' WITH GRANT OPTION;
  • Сайт
  • Об Ubuntu
  • Скачать Ubuntu
  • Семейство Ubuntu
  • Новости
  • Форум
  • Помощь
  • Правила
  • Документация
  • Пользовательская документация
  • Официальная документация
  • Семейство Ubuntu
  • Материалы для загрузки
  • Совместимость с оборудованием
  • RSS лента
  • Сообщество
  • Наши проекты
  • Местные сообщества
  • Перевод Ubuntu
  • Тестирование
  • RSS лента
Читайте также:  Linux task manager command

© 2018 Ubuntu-ru — Русскоязычное сообщество Ubuntu Linux.
© 2012 Canonical Ltd. Ubuntu и Canonical являются зарегистрированными торговыми знаками Canonical Ltd.

Источник

Install and Configure Apache

Apache is an open source web server that’s available for Linux servers free of charge.

In this tutorial we’ll be going through the steps of setting up an Apache server.

What you’ll learn

What you’ll need

  • Ubuntu Server 16.04 LTS
  • Secure Shell (SSH) access to your server
  • Basic Linux command line knowledge

Got everything ready? Let’s move on to the next step!

Originally authored by Aden Padilla

2. Installing Apache

To install Apache, install the latest meta-package apache2 by running:

sudo apt update sudo apt install apache2 

After letting the command run, all required packages are installed and we can test it out by typing in our IP address for the web server.

Apache-Installed

If you see the page above, it means that Apache has been successfully installed on your server! Let’s move on.

3. Creating Your Own Website

By default, Apache comes with a basic site (the one that we saw in the previous step) enabled. We can modify its content in /var/www/html or settings by editing its Virtual Host file found in /etc/apache2/sites-enabled/000-default.conf .

We can modify how Apache handles incoming requests and have multiple sites running on the same server by editing its Virtual Hosts file.

Today, we’re going to leave the default Apache virtual host configuration pointing to www.example.com and set up our own at gci.example.com .

So let’s start by creating a folder for our new website in /var/www/ by running

We have it named gci here but any name will work, as long as we point to it in the virtual hosts configuration file later.

Читайте также:  Linux kyocera fs c8525mfp

Now that we have a directory created for our site, lets have an HTML file in it. Let’s go into our newly created directory and create one by typing:

cd /var/www/gci/ nano index.html 

Paste the following code in the index.html file:

      

I'm running this website on an Ubuntu Server server!

Now let’s create a VirtualHost file so it’ll show up when we type in gci.example.com .

4. Setting up the VirtualHost Configuration File

We start this step by going into the configuration files directory:

cd /etc/apache2/sites-available/ 

Since Apache came with a default VirtualHost file, let’s use that as a base. ( gci.conf is used here to match our subdomain name):

sudo cp 000-default.conf gci.conf 

Now edit the configuration file:

We should have our email in ServerAdmin so users can reach you in case Apache experiences any error:

ServerAdmin yourname@example.com 

We also want the DocumentRoot directive to point to the directory our site files are hosted on:

The default file doesn’t come with a ServerName directive so we’ll have to add and define it by adding this line below the last directive:

This ensures people reach the right site instead of the default one when they type in gci.example.com .

Now that we’re done configuring our site, let’s save and activate it in the next step!

5. Activating VirtualHost file

After setting up our website, we need to activate the virtual hosts configuration file to enable it. We do that by running the following command in the configuration file directory:

You should see the following output

Enabling site gci. To activate the new configuration, you need to run: service apache2 reload root@ubuntu-server:/etc/apache2/sites-available# 

To load the new site, we restart Apache by typing:

End result

Final

Now is the moment of truth, let’s type our host name in a browser. Hooray!

Further reading:

Источник

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