> For the complete documentation index, see [llms.txt](https://spacecore.gitbook.io/wiki/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://spacecore.gitbook.io/wiki/ua/web-development/install-nginx.md).

# Встановлення Nginx

Nginx - це вебсервер з безліччю функцій, створений відповідно до останніх канонів технологій. Його використовують найбільші компанії, такі як ВКонтакте, Google, Facebook та інші.

{% hint style="warning" %}
Перед встановленням переконайтеся, що у вас не встановлений Apache2!
{% endhint %}

### Встановлення вебсерверу

Його встановлення надзвичайно просте, скористайтесь наступною командою:

```
apt-get install nginx -y
```

## Налаштування Nginx

Необхідно перейти до каталогу /etc/nginx/sites-available і створити файл на зразок «site.conf».&#x20;

Вставте наступне в конфігураційний файл та відредагуйте:

{% code title="site.conf" %}

```
server {
    listen       *:80;
    server_name  spacecore.pro; # домен сайту
    client_max_body_size 1000M; # максимальний розмір файлу, що передається через сайт
    error_page 404 = @notfound;
    location / {
        root   /home/site/spacecore; # шлях до сайту
        try_files $uri $uri.html $uri/ @extensionless-php;
        index  index.html index.php;
    }
    # Підключення PHP, якщо вам це не потрібно, видаліть рядки з 13 по 21
    location ~ \.(php|html|htm)$ {
        try_files $uri =404;
        root   /home/site/spacecore; # шлях до сайту
        fastcgi_pass unix:/run/php/php7.0-fpm.sock; # шлях до php
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $request_filename;
        include /etc/nginx/fastcgi_params;
    }
}
```

{% endcode %}

Перезапуск Nginx:

```
service nginx restart
```

## Примітки щодо PHP

{% hint style="info" %}
PHP не обов'язковий для роботи з Nginx. Ця примітка важлива лише для тих, чий сайт використовує PHP. Додаткову інформацію можна [знайти тут](https://wiki.spacecore.pro/v/ua/web-development/install-php).
{% endhint %}

### Підключення SSL-сертифікату до Nginx

{% hint style="info" %}
SSL-з'єднання не є обов'язковим, воно здійснюється за наявності та за вашим бажанням.
{% endhint %}

Потрібно створити або відредагувати конфігураційний файл сайту, щоб він виглядав так:

```
server {
server {
    listen 80;
    server_name spacecore.pro; # домен сайту
    return 301 https://$server_name$request_uri; # перенаправлення з http на https
}

server {
    listen 443 ssl http2;
    server_name spacecore.pro; # домен сайту

    root /var/www/spacecore; # шлях до сайту
    index index.html index.htm index.php; # індексні сторінки

    access_log /var/log/nginx/spacecore.app-access.log; # логи успішних з'єднань
    error_log  /var/log/nginx/spacecore.app-error.log error; # логи помилкових з'єднань

    # якщо хочете відключити щось, замість шляху до файлу напишіть «off»

    client_max_body_size 1000m; # максимальний розмір файлу, що передається через сайт
    client_body_timeout 120s; # значення таймауту

    sendfile off; # після увімкнення Nginx відправлятиме заголовки HTTP-відповідей одним пакетом, а не окремими частинами.
    # Налаштування SSL
    ssl_certificate /etc/letsencrypt/live/spacecore.pro/fullchain.pem; # публічний ключ сертифікату
    ssl_certificate_key /etc/letsencrypt/live/spacecore.pro/privkey.pem; # приватний ключ сертифікату
    ssl_session_cache shared:SSL:10m; # розмір кешу сесій SSL
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384";
    ssl_prefer_server_ciphers on; # зменшує час завантаження сторінок сайту

    location ~ \.(php|html|htm)$ {
        try_files $uri =404;
        root /var/www/spacecore; # шлях до сайту
        fastcgi_pass unix:/run/php/php7.2-fpm.sock; # шлях до php
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $request_filename;
        include /etc/nginx/fastcgi_params;
    }
}
```

Перезавантаження Nginx:

```
service nginx restart
```

## Перевірка Apache2

Якщо Nginx встановлено разом з Apache2, вони будуть конфліктувати через порт 80. Тому потрібно видалити один з вебсерверів. Перевірте, чи встановлений Apache2:

```
service apache2 status
```

{% hint style="info" %}
Якщо не видно великого повідомлення з інформацією, то він не встановлений.
{% endhint %}

Якщо Apache2 встановлений, потрібно його видалити:

```
apt-get remove --purge apache2* -y
```

## Видалення Nginx

Щоб повністю видалити Nginx з сервера, його потрібно спершу зупинити:

```
service nginx stop
```

А потім виконати команду, яка видалить його назавжди:

```
apt-get remove --purge nginx*
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://spacecore.gitbook.io/wiki/ua/web-development/install-nginx.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
