Welcome to nginx on debian что это

Обновлено: 07.07.2024

In this guide, we will install Nginx on your Debian 8 server.

Prerequisites

To follow this tutorial, you will need:

  • One fresh Debian 8.1 Droplet
  • A sudo non-root user, which you can setup by following steps 2 and 3 of this tutorial

Unless otherwise noted, all of the commands in this tutorial should be run as a non-root user with sudo privileges.

Step 1 — Install Nginx

In this step, we will use a built-in package installer called apt-get . It simplifies management drastically and facilitates a clean installation.

As part of the prerequisites, you should have updated the apt package index with apt-get and installed the sudo package. Unlike other Linux distributions, Debian 8 does not come with sudo installed.

For information on the differences between Nginx and Apache2, the two most popular open-source web servers, see this article.

Step 2 — Test Your Web Server

In this step, we will test that your Nginx server is accessible.

Nginx Default Page on Debian 8

If you do not have access to a web browser, you can still test your server from the command line. It is best to test it from a different system to make sure your website is visible to the outside world. Issue the command:

You should see the following HTML output.

An error would have looked like the following. You should not see this.

Step 3 — Manage the Nginx Process

Now that you have your web server up and running, we can go over some basic management commands.

To stop your web server, you can type:

To start the web server when it is stopped, type:

To stop and then start the service again, type:

If you are simply making configuration changes, Nginx can often reload without dropping connections. To do this, this command can be used:

We can make sure that our web server will restart automatically when the server is rebooted by typing:

To test that this configuration works, restart your server.

Then logout, as the server is now restarting.

After a minute or two, you may repeat Step 2 to test that your web server starts on reboot.

Server Root and Configuration

If you want to start serving your own pages or application through Nginx, you will want to know the locations of the Nginx configuration files and default server root directory.

Default Server Root

The default server root directory is /var/www/html . Files that are placed in this directory will be served on your web server. This location is specified in the default server block configuration file that ships with Nginx, which is located at /etc/nginx/sites-enabled/default .

Server Block Configuration

Any additional server blocks, known as Virtual Hosts in Apache, can be added by creating new configuration files in /etc/nginx/sites-available . To activate these configurations, create a symbolic link to /etc/nginx/sites-enabled , using the following:

All configuration files in the sites-enabled directory will be loaded by Nginx.

Nginx Global Configuration

The main Nginx configuration file is located at /etc/nginx/nginx.conf . This is where you can change settings like the user that runs the Nginx daemon processes, and the number of worker processes that get spawned when Nginx is running, among other things.

Conclusion

Now that you have your web server installed, you have many options for the type of content to serve and the technologies you want to use to create a richer experience.

You may also want to explore additional options to secure your server. Remember that it is now open to the world wide web and is extremely vulnerable.

Welcome to NGINX screen

The Welcome to nginx! page is the default web page that is presented when a website operator has installed the NGINX web server software on a computer on the Internet, and either the NGINX configuration is not yet complete or a problem at the website itself is preventing the correct content from appearing.

The NGINX software has not been installed on your computer – it runs only on computers that are serving web pages. NGINX is not a virus and has nothing to do with determining which websites your browser accesses. Read on for more details.

Why Am I Seeing this Page?

When you see the Welcome to nginx! page, the mostly likely reason is that there is a configuration or other problem at the website. In this case, about all you can do is wait for the problem to be fixed by the website administrator.

Less often, there might be a problem on your computer that is causing your web browser to go to the wrong website.

It might be a temporary problem, in which case it might help to clear your browser cache and history, then restart your computer and home router if necessary. See What Should I Do?.

It is also possible that your computer has a virus or other malware that is intercepting your web requests and directing you to the wrong website.

Again, the NGINX software has not been installed on your computer – it runs only on computers that are serving web pages. NGINX is not a virus and has nothing to do with determining which websites your browser accesses.

What Should I Do?

To investigate whether the problem is on your computer, we recommend that you do the following. After each step, test whether the problem is fixed:

If you feel like investigating further, below are some other things for a knowledgeable user to try.

Run a Reputable Virus Scanner

Run a scanner or anti-malware application from a security software company. Users of Windows 8.1 and later can use Windows Defender, which is free antimalware software included with Windows. Windows 7 users can use Microsoft Security Essentials.

Most Linux distributions and BSD variants have NGINX in the usual package repositories and they can be installed via whatever method is normally used to install software ( apt on Debian, emerge on Gentoo, ports on FreeBSD, etc).

Official Red Hat/CentOS packages¶

To add NGINX yum repository, create a file named /etc/yum.repos.d/nginx.repo and paste one of the configurations below:

Due to differences between how CentOS, RHEL, and Scientific Linux populate the $releasever variable, it is necessary to manually replace $releasever with either 5 (for 5.x) or 6 (for 6.x), depending upon your OS version.

Official Debian/Ubuntu packages¶

The available NGINX Ubuntu release support is listed at this distribution page. For a mapping of Ubuntu versions to release names, please visit the Official Ubuntu Releases page.

Append the appropriate stanza to /etc/apt/sources.list . If there is concern about persistence of repository additions (i.e. DigitalOcean Droplets), the appropriate stanza may instead be added to a different list file under /etc/apt/sources.list.d/ , such as /etc/apt/sources.list.d/nginx.list .

e.g. Ubuntu 20.04 (Focal Fossa):

To install the packages, execute in your shell:

You have now nginx installed on your server but not ready to serve web pages. you have to start the nginx. You can do this by using this command:

Append the appropriate stanza to /etc/apt/sources.list .

Ubuntu PPA¶

You can get the latest stable version of NGINX from the NGINX PPA on Launchpad: You will need to have root privileges to perform the following commands.

For Ubuntu 20.04 and newer:

If you get an error about add-apt-repository not existing, you will want to install python-software-properties . For other Debian/Ubuntu based distributions, you can try the lucid variant of the PPA which is the most likely to work on older package sets:

Official Win32 Binaries¶

As of NGINX 0.8.50, NGINX is now available as an official Windows binary.

For problems look in c:nginxlogserror.log or in EventLog.

In addition, Kevin Worthington maintains earlier Windows builds of the development branch.

Source Releases¶

There are currently two versions of NGINX available: stable (1.20.x) , mainline (1.21.x) . The mainline branch gets new features and bugfixes sooner but might introduce new bugs as well. Critical bugfixes are backported to the stable branch.

In general, the stable release is recommended, but the mainline release is typically quite stable as well. See the FAQ .

Nginx — один из самых популярных веб-серверов в мире. На веб-серверах Nginx размещены некоторые самые крупные сайты в Интернете с самым высоким уровнем трафика. Обычно он использует ресурсы эффективнее, чем Apache, и может использоваться как веб-сервер или обратный прокси-сервер.

В этом обучающем модуле мы расскажем, как установить Nginx на сервере Debian 9.

Предварительные требования

Для прохождения этого обучающего модуля вам потребуется настроенный на сервере пользователь без привилегий root с привилегиями sudo, а также активный брандмауэр. Подробнее об этом можно узнать в обучающем модуле Начальная настройка сервера для Debian 9.

Создав учетную запись, войдите в систему как пользователь без привилегий root.

Шаг 1 — Установка Nginx

Поскольку Nginx доступен в репозиториях Debian по умолчанию, его можно установить из этих репозиториев с помощью системы пакетов apt .

Поскольку это первое наше взаимодействие с системой пакетов apt в этом сеансе, мы также обновим индекс локальных пакетов, чтобы получить доступ к актуальным спискам пакетов. Затем мы можем выполнить установку nginx :

После принятия процедуры apt выполнит установку Nginx и других требуемых зависимостей на ваш сервер.

Шаг 2 — Настройка брандмауэра

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

Для вывода списка конфигураций приложений, которые известны ufw , необходимо ввести следующую команду:

Необходимо получить список профилей приложений:

Как видите, для Nginx доступны три профиля:

Рекомендуется применять самый ограничивающий профиль, который будет разрешать заданный трафик. Поскольку в этом модуле мы еще не настроили SSL для нашего сервера, нам нужно будет только разрешить трафик на порте 80 .

Для активации можно ввести следующую команду:

Для проверки изменений введите:

Шаг 3 — Проверка веб-сервера

В конце процесса установки Debian 9 запускает Nginx. Веб-сервер уже должен быть запущен и работать.

Используйте команду systemd init system , чтобы проверить работу службы:

Как видно из результатов выполнения команды, служба успешно запущена. Однако лучше всего протестировать ее запуск посредством запроса страницы из Nginx.

Откройте страницу Nginx по умолчанию, чтобы подтвердить работу программного обеспечения через IP-адрес вашего сервера. Если вы не знаете IP-адрес своего сервера, введите в командную строку следующую команду:

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

Когда вы узнаете IP-адрес вашего сервера, введите его в адресную строку браузера:

Вы увидите начальную страницу Nginx по умолчанию:

Эта страница включена в Nginx и показывает правильную работу сервера.

Шаг 4 — Управление процессом Nginx

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

Чтобы остановить веб-сервер, введите:

Чтобы запустить остановленный веб-сервер, введите:

Чтобы остановить и снова запустить службу, введите:

Если вы просто вносите изменения в конфигурацию, во многих случаях Nginx может перезагружаться без отключения соединений. Для этого введите:

По умолчанию Nginx настроен на автоматический запуск при загрузке сервера. Если вы не хотите этого, вы можете отключить такое поведение с помощью следующей команды:

Чтобы перезагрузить службу для запуска во время загрузки, введите:

Шаг 5 — Настройка блоков сервера

Затем назначьте владение директорией с помощью переменной среды $USER :

Разрешения корневых директорий веб-сервера должны быть правильными, если вы не изменяли значение umask . Тем не менее вы можете проверить это с помощью следующей команды:

Затем создайте в качестве примера страницу index.html , используя nano или свой любимый редактор:

Добавьте в страницу следующий образец кода HTML:

Сохраните файл и закройте его после завершения.

Введите следующий блок конфигурации, который похож на заданный по умолчанию, но обновлен с учетом новой директории и доменного имени:

Мы обновили конфигурацию root с указанием новой директории и заменили server_name на имя нашего домена.

Теперь мы активируем файл, создав ссылку в директории sites-enabled , который Nginx считывает при запуске:

Два серверных блока активированы и настроены для реагирования на запросы на основе директив listen и server_name (дополнительную информацию об обработке Nginx этих директив можно найти здесь):

Чтобы избежать возможной проблемы с хэшированием памяти при добавлении дополнительных имен серверов, необходимо изменить одно значение в файле /etc/nginx/nginx.conf . Откройте файл:

Сохраните файл и закройте его после завершения.

Проведите тестирования, чтобы убедиться в отсутствии ошибок синтаксиса в файлах Nginx:

Если проблем нет, вы увидите на экране следующие результаты:

После тестирования конфигурации перезапустите Nginx для активации изменений:

Первый серверный блок Nginx

Шаг 6 — Знакомство с важными файлами и директориями Nginx

Теперь вы научились управлять службой Nginx, и настало время познакомиться с несколькими важными директориями и файлами.

Контент

  • /var/www/html : веб-контент, в состав которого по умолчанию входит только показанная ранее страница Nginx по умолчанию, выводится из директории /var/www/html . Это можно изменить путем изменения файлов конфигурации Nginx.

Конфигурация сервера

  • /etc/nginx : директория конфигурации Nginx. Здесь хранятся все файлы конфигурации Nginx.
  • /etc/nginx/nginx.conf : основной файл конфигурации Nginx. Его можно изменить для внесения изменений в глобальную конфигурацию Nginx.
  • /etc/nginx/sites-available/ : директория, где могут храниться серверные блоки для каждого сайта. Nginx не будет использовать файлы конфигурации из этой директории, если они не будут связаны с директорией sites-enabled . Обычно конфигурации серверных блоков записываются в эту директорию и активируются посредством ссылки на другую директорию.
  • /etc/nginx/sites-enabled/ : директория, где хранятся активные серверные блоки каждого узла. Они созданы посредством ссылки на файлы конфигурации в директории sites-available .
  • /etc/nginx/snippets : в этой директории содержатся фрагменты конфигурации, которые можно включить в конфигурацию Nginx. Воспроизводимые сегменты конфигурации хорошо подходят для преобразования в сниппеты.

Журналы сервера

  • /var/log/nginx/access.log : каждый запрос к вашему веб-серверу регистрируется в этом файле журнала, если Nginx не настроен иначе.
  • /var/log/nginx/error.log : любые ошибки Nginx будут регистрироваться в этом журнале.

Заключение

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

Читайте также: