Welcome to nginx on red hat enterprise linux

Install

Binary ReleasesВ¶

Prebuilt Packages for Linux and BSDВ¶

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).

Be aware that these packages are often somewhat out-of-date. If you want the latest features and bugfixes, it’s recommended to build from source or use packages directly from nginx.org.

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:

If a W: GPG error: https://nginx.org/packages/ubuntu focal InRelease: The following signatures couldn’t be verified because the public key is not available: NO_PUBKEY $key is encountered during the NGINX repository update, execute the following:

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В¶

This PPA is maintained by volunteers and is not distributed by nginx.org. It has some additional compiled-in modules and may be more fitting for your environment.

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 .

Источник

Вместо сайта Welcome to NGinx,что делать?

Папки /var/www нету. Data-www не нашёл.
Откуда он берёт приветствие Welcome to NGinx?
И где директория где находится контент сайта?

  • Вопрос задан более трёх лет назад
  • 7468 просмотров

1)Остановил NGinx
2)Создал файл /home/user/logs/nginx.access.log потому что NGinx очковал что его нет
3)Перезапустил NGinx
4)PROFIT! Теперь он читает мой index!

Эта инструкция решает мою проблему и проблему с незапуском NGinx по причине того что он не может найти PID файл!

То есть эта инструкция решает следующие проблемы:
NGinx не может найти PID файл
NGinx не находит нужный файл
NGinx не хочет запускаться

Папки /var/www нету. Data-www не нашёл.

Так создайте каталог, если его нет.

www-data (а не Data-www) — имя группы.

И что он должен показать, если контент не создали? Страницу из пакета и показывает.

Tostich: Посмотрел содержимое пакета. У Вас что-то сломано в системе, если не было каталога /var/www. Он должен был создаться при установке пакета.

Читайте также:  Как посмотреть последние открытые файлы windows

И что «не помогло»? Если пишете о проблеме, описывайте, что делали.

AVKor: Создал каталог /var/www и загрузил в него index.html
Не отображается содержание index.html,вместо этого Welcome to nginx.

Выполнил команду apt-get install nginx и всё.

Источник

Установка Nginx в CentOS 8

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

Данный мануал поможет установить Nginx на сервер CentOS 8.

Требования

Для работы нужен сервер CentOS 8, настроенный по этому мануалу.

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

Пакет Nginx можно установить с помощью dnf, нового стандартного пакетного менеджера CentOS 8.

Чтобы установить Nginx, введите эту команду:

sudo dnf install nginx

Чтобы подтвердить установку, введите y. После этого dnf установит Nginx и все его зависимости на ваш сервер.

После завершения установки вам нужно добавить веб-сервер в автозагрузку и запустить его:

sudo systemctl enable nginx
sudo systemctl start nginx

2: Настройка брандмауэра

Прежде чем запустить Nginx, нужно настроить брандмауэр firewalld для поддержки его трафика через порт 80.

Чтобы на постоянной основе активировать соединения HTTP по порту 80, введите эту команду:

sudo firewall-cmd —permanent —add-service=http

Чтобы убедиться в том, что брандмауэр пропускает трафик http, запустите:

sudo firewall-cmd —permanent —list-all

Вы увидите такой вывод, если все работает правильно:

public
target: default
icmp-block-inversion: no
interfaces:
sources:
services: cockpit dhcpv6-client http ssh
ports:
protocols:
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:

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

sudo firewall-cmd —reload

После этого ваш сервер Nginx полностью готов к работе с внешними пользователями.

3: Тестирование веб-сервера

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

Если у вас нет домена, а своего IP-адреса вы не знаете, вы можете узнать его с помощью командной строки. Введите:

ip addr show eth0 | grep inet | awk ‘< print $2; >‘ | sed ‘s/\/.*$//’

Команда вернёт несколько строк. Проверьте каждый полученный адрес в браузере.

В качестве альтернативы вы можете проверить, как ваш сервер видят другие точки в интернете. Для этого используйте команду:

curl -4 icanhazip.com

Узнав свой IP-адрес, введите его в браузер, чтобы убедиться, что веб-сервер работает должным образом.

На экране должна появиться стандартная страница Nginx:

Welcome to nginx on Red Hat Enterprise Linux!
This page is used to test the proper operation of the nginx HTTP server after it has been installed […]

Если вы видите такую страницу, ваш веб-сервер работает правильно.

4: Управление процессами Nginx

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

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

sudo systemctl stop nginx

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

sudo systemctl start nginx

Для перезапуска используйте эту команду:

sudo systemctl restart nginx

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

sudo systemctl reload nginx

По умолчанию Nginx автоматически запускается вместе с сервером. Это поведение можно выключить при помощи команды:

sudo systemctl disable nginx

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

sudo systemctl enable nginx

5: Важные файлы и каталоги Nginx

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

  • /usr/share/nginx/html: содержит текущий контент сайта. По умолчанию в нём находится только стандартная посадочная страница, которую вы уже видели. Этот каталог можно изменить в конфигурационном файле Nginx.
  • /etc/nginx: каталог настроек nginx, в котором хранятся все конфигурационные файлы.
  • /etc/nginx/nginx.conf: главный конфигурационный файл Nginx, содержащий глобальные настройки веб-сервера.
  • /etc/nginx/conf.d/: каталог для хранения виртуальных хостов, которые в контексте Nginx называются блоками server. Как правило, они нужны для того, чтобы обслуживать разные домены в рамках одного сервера. Обычно имя файла виртуального хоста совпадает с доменом сайта, для которого он предназначен (по формату your_domain.conf).
  • /var/log/nginx/access.log: регистрирует все запросы, полученные веб-сервером Nginx (если не настроено другое поведение).
  • /var/log/nginx/error.log: хранит все сообщения об ошибках Nginx.

6: Настройка виртуального хоста (опционально)

На веб-сервере Nginx можно использовать виртуальные хосты (также они называются блоками server) для размещения нескольких доменов на одном сервере и изоляции их настроек.

Примечание: Здесь мы используем условный домен your_domain, а вы должны заменить его собственным доменом.

В CentOS 8 файлы блоков server хранятся в каталоге /etc/nginx/conf.d в формате .conf. В этой системе Nginx по умолчанию обслуживает документы из каталога /usr/share/nginx/html. Этого хватит для одного сайта, но если вы хотите разместить несколько сайтов, вам нужно создать новые виртуальные хосты.

Мы не будем редактировать стандартный каталог /usr/share/nginx/html, вместо этого мы создадим каталог /var/www для тестового сайта your_domain (а /usr/share/nginx/html останется как каталог по умолчанию, который будет обслуживаться, если запрос клиента не соответствует другим сайтам).

Читайте также:  Обзор ldap каталогов для linux

Создайте каталог для your_domain, используя опцию -p для создания всех необходимых родительских каталогов:

sudo mkdir -p /var/www/your_domain/html

Затем установите права на каталог с помощью переменной $USER:

sudo chown -R $USER:$USER /var/www/your_domain/html

Затем создайте образец страницы index.html с помощью текстового редактора. В CentOS 8 по умолчанию установлен редактор vi. Он очень мощный, но новичкам с ним бывает трудно работать. При желании вы можете установить редактор nano, он немного проще:

sudo dnf install nano

Теперь с его помощью создайте файл index.html:

Вставьте в файл такой HTML-код:

Success! Your Nginx server is successfully configured for your_domain.

Источник

Red Hat Customer Portal

Log in to Your Red Hat Account

Your Red Hat account gives you access to your profile, preferences, and services, depending on your status.

If you are a new customer, register now for access to product evaluations and purchasing capabilities.

Need access to an account?

If your company has an existing Red Hat account, your organization administrator can grant you access.

Red Hat Account

Customer Portal

For your security, if you’re on a public computer and have finished using your Red Hat services, please be sure to log out.

Select Your Language

Red Hat Training

A Red Hat training course is available for RHEL 8

Chapter 2. Setting up and configuring NGINX

NGINX is a high performance and modular server that you can use, for example, as a:

  • Web server
  • Reverse proxy
  • Load balancer

This section describes how to NGINX in these scenarios.

2.1. Installing and preparing NGINX

Red Hat uses Application Streams to provide different versions of NGINX. This section describes how to:

  • Select a stream and install NGINX
  • Open the required ports in the firewall
  • Enable and start the nginx service

Using the default configuration, NGINX runs as a web server on port 80 and provides content from the /usr/share/nginx/html/ directory.

Prerequisites

  • RHEL 8 is installed.
  • The host is subscribed to the Red Hat Customer Portal.
  • The firewalld service is enabled and started.

Procedure

Display the available NGINX module streams:

If you want to install a different stream than the default, select the stream:

Install the nginx package:

Open the ports on which NGINX should provide its service in the firewall. For example, to open the default ports for HTTP (port 80) and HTTPS (port 443) in firewalld , enter:

Enable the nginx service to start automatically when the system boots:

Optionally, start the nginx service:

If you do not want to use the default configuration, skip this step, and configure NGINX accordingly before you start the service.

Verification steps

Use the yum utility to verify that the nginx package is installed:

Ensure that the ports on which NGINX should provide its service are opened in the firewalld:

Verify that the nginx service is enabled:

Additional resources

  • For details about Subscription Manager, see the Using and Configuring Subscription Manager guide.
  • For further details about Application Streams, modules, and installing packages, see the Installing, managing, and removing user-space components guide.
  • For details about configuring firewalls, see the Securing networks guide.

2.2. Configuring NGINX as a web server that provides different content for different domains

By default, NGINX acts as a web server that provides the same content to clients for all domain names associated with the IP addresses of the server. This procedure explains how to configure NGINX:

  • To serve requests to the example.com domain with content from the /var/www/example.com/ directory
  • To serve requests to the example.net domain with content from the /var/www/example.net/ directory
  • To serve all other requests, for example, to the IP address of the server or to other domains associated with the IP address of the server, with content from the /usr/share/nginx/html/ directory

Prerequisites

Clients and the web server resolve the example.com and example.net domain to the IP address of the web server.

Note that you must manually add these entries to your DNS server.

Procedure

Edit the /etc/nginx/nginx.conf file:

By default, the /etc/nginx/nginx.conf file already contains a catch-all configuration. If you have deleted this part from the configuration, re-add the following server block to the http block in the /etc/nginx/nginx.conf file:

These settings configure the following:

  • The listen directive define which IP address and ports the service listens. In this case, NGINX listens on port 80 on both all IPv4 and IPv6 addresses. The default_server parameter indicates that NGINX uses this server block as the default for requests matching the IP addresses and ports.
  • The server_name parameter defines the host names for which this server block is responsible. Setting server_name to _ configures NGINX to accept any host name for this server block.
  • The root directive sets the path to the web content for this server block.
Читайте также:  Код активации windows sp1

Append a similar server block for the example.com domain to the http block:

  • The access_log directive defines a separate access log file for this domain.
  • The error_log directive defines a separate error log file for this domain.

Append a similar server block for the example.net domain to the http block:

Create the root directories for both domains:

Set the httpd_sys_content_t context on both root directories:

These commands set the httpd_sys_content_t context on the /var/www/example.com/ and /var/www/example.net/ directories.

Note that you must install the policycoreutils-python-utils package to run the restorecon commands.

Create the log directories for both domains:

Restart the nginx service:

Verification steps

Create a different example file in each virtual host’s document root:

  • Use a browser and connect to http://example.com . The web server shows the example content from the /var/www/example.com/index.html file.
  • Use a browser and connect to http://example.net . The web server shows the example content from the /var/www/example.net/index.html file.
  • Use a browser and connect to http:// IP_address_of_the_server . The web server shows the example content from the /usr/share/nginx/html/index.html file.
  • 2.3. Adding TLS encryption to an NGINX web server

    This section describes how to enable TLS encryption on an NGINX web server for the example.com domain.

    Prerequisites

    The private key is stored in the /etc/pki/tls/private/example.com.key file.

    For details about creating a private key and certificate signing request (CSR), as well as how to request a certificate from a certificate authority (CA), see your CA’s documentation.

  • The TLS certificate is stored in the /etc/pki/tls/certs/example.com.crt file. If you use a different path, adapt the corresponding steps of the procedure.
  • The CA certificate has been appended to the TLS certificate file of the server.
  • Clients and the web server resolve the host name of the server to the IP address of the web server.
  • Port 443 is open in the local firewall.
  • Procedure

    Edit the /etc/nginx/nginx.conf file, and add the following server block to the http block in the configuration:

    For security reasons, configure that only the root user can access the private key file:

    If the private key was accessed by unauthorized users, revoke the certificate, create a new private key, and request a new certificate. Otherwise, the TLS connection is no longer secure.

    Restart the nginx service:

    Verification steps

    • Use a browser and connect to https://example.com

    Additional resources

    2.4. Configuring NGINX as a reverse proxy for the HTTP traffic

    You can configure the NGINX web server to act as a reverse proxy for HTTP traffic. For example, you can use this functionality to forward requests to a specific subdirectory on a remote server. From the client perspective, the client loads the content from the host it accesses. However, NGINX loads the actual content from the remote server and forwards it to the client.

    This procedure explains how to forward traffic to the /example directory on the web server to the URL https://example.com .

    Prerequisites

    • NGINX is installed as described in Section 2.1, “Installing and preparing NGINX”.
    • Optional: TLS encryption is enabled on the reverse proxy.

    Procedure

    Edit the /etc/nginx/nginx.conf file and add the following settings to the server block that should provide the reverse proxy:

    The location block defines that NGINX passes all requests in the /example directory to https://example.com .

    Set the httpd_can_network_connect SELinux boolean parameter to 1 to configure that SELinux allows NGINX to forward traffic:

    Restart the nginx service:

    Verification steps

    • Use a browser and connect to http:// host_name /example and the content of https://example.com is shown.

    2.5. Configuring NGINX as an HTTP load balancer

    You can use the NGINX reverse proxy feature to load-balance traffic. This procedure describes how to configure NGINX as an HTTP load balancer that sends requests to different servers, based on which of them has the least number of active connections. If both servers are not available, the procedure also defines a third host for fallback reasons.

    Prerequisites

    Procedure

    Edit the /etc/nginx/nginx.conf file and add the following settings:

    The least_conn directive in the host group named backend defines that NGINX sends requests to server1.example.com or server2.example.com , depending on which host has the least number of active connections. NGINX uses server3.example.com only as a backup in case that the other two hosts are not available.

    With the proxy_pass directive set to http://backend , NGINX acts as a reverse proxy and uses the backend host group to distribute requests based on the settings of this group.

    Instead of the least_conn load balancing method, you can specify:

    Источник

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