Updated 14 April 2021


Installing and setting up Nginx

First install Nginx:

emerge -a www-servers/nginx

Nginx configuration

Все настройки как самого Nginx прописываются в файле /etc/nginx/nginx.conf. Параметры для сайтов хранятся в каталоге /etc/nginx/sites-enabled.

Самоподписной сертификат

При установке пакета www-servers/nginx, самоподписной сертификат создаётся автоматически сроком на 10 лет. Для перегенерации его выполните:

openssl req -x509 -subj "/CN=_" -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt

Запустите Nginx:

/etc/init.d/nginx start

Add Nginx to autostart:

rc-update add nginx

Запрет обработки неописанных сайтов

Выполните настройку, чтобы Nginx на неописанные сайты закрывал соединение без ответа.


server {
    listen  80 default_server;
    server_name _;
    access_log /var/log/nginx/noname_80.access_log main;
    return      444;
server {
    listen 443 ssl default_server;
    ssl_ciphers aNULL;
    ssl_certificate /etc/nginx/ssl/nginx.crt;
    ssl_certificate_key /etc/nginx/ssl/nginx.key;
    ssl_session_tickets off;
    server_name _;
    access_log /var/log/nginx/noname_443.access_log main;
    return      444;

Перезагрузите настройки Nginx:

/etc/init.d/nginx reload

Examples of Nginx configuration

Create a config file for localhost:

server {
    # Порт, на котором работает ресурс
    listen 80;
    # Название ресурса, по которому будет осуществляться доступ
    server_name localhost;
    # Пути, по которым будут записываться логи
    access_log /var/log/nginx/localhost.access_log main;
    error_log /var/log/nginx/localhost.error_log info;
    # Корневая папка ресурса
    root /var/calculate/www/localhost/htdocs;

Create an index file to check the health of the server:

mkdir -p /var/calculate/www/localhost/htdocs

echo 'Hello!' > /var/calculate/www/localhost/htdocs/index.html

Проверка настроек

Перед тем, как перезапускать службу Nginx, всегда выполняйте проверку правильности сделанных изменений командой nginx -t

Если всё верно, то будет выведено следующее:

nginx -t

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

If this was successful, reread the Nginx configuration:

/etc/init.d/nginx reload

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

curl http://localhost


Configuring reverse proxy on Nginx

A reverse proxy is usually understood as a server that receives a request from a client but does not process it independently, but sends it in whole or in part to other (upstream) servers for processing. In other words, it does not redirect the client, but sends a request on its own and then sends back the answer to the client.

Configure a reverse proxy that communicates with the internal HTTP service running on port 8080:

server {
  listen 80;
  access_log /var/log/nginx/proxy.log;

  location / {

Configuring HTTPS for Nginx

Create a DH key:

openssl dhparam -out /etc/nginx/ssl-dhparams.pem 4096
Generating DH parameters, 4096 bit long safe prime, generator 2
This is going to take a long time

Create a file describing the general SSL parameters:

# This file contains important security parameters. If you modify this file
# manually, Certbot will be unable to automatically provide future security
# updates. Instead, Certbot will print and log an error message with a path to
# the up-to-date file that you will need to refer to when manually updating
# this file.

ssl_session_cache shared:le_nginx_SSL:1m;
ssl_session_timeout 1440m;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;


ssl_dhparam /etc/nginx/ssl-dhparams.pem;

Getting a Let's Encrypt certificate

Get the and domain certificates for Nginx, as described in the manual.

Example of HTTPS configuration

Add HTTPS settings for

server {
    listen 80;
    listen 443 ssl;

    include ssl.conf;
    ssl_certificate /etc/letsencrypt/live/;
    ssl_certificate_key /etc/letsencrypt/live/;

    access_log /var/log/nginx/ main;
    error_log /var/log/nginx/ info;

    include acme.conf;

    root /var/calculate/www/;

Installing and configuring PHP-FPM

PHP-FPM (FastCGI Process Manager) is a high-performance and scalable interface for interaction between a web server and a web application, a further development of the CGI technology.
The main advantage of FastCGI is the separation between the dynamic language and the web server. This technology allows you to run Web servers and CGI processes on multiple hosts, thus improving scalability and security without noticeable loss of performance.

To install PHP-FPM, run:

emerge -a dev-lang/php

Once all the relevant information is displayed for installation, you must accept the default version of PHP. You can cancel the installation and specify the required version of PHP at the next installation try. Use php -m to display all available and running extensions.

Использование UNIX-сокета для взаимодействия Nginx c PHP является предпочтительным и рекомендуемым вариантом!

Edit the pool for handling the sites for which this socket will be specified in the configuration:

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
user = nginx
group = nginx

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   ''    - to listen on a TCP socket to a specific IPv4 address on
;                            a specific port;
;   '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all addresses
;                            (IPv6 and IPv4-mapped) on a specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = /run/php-fpm.socket

; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server. Many
; BSD-derived systems allow connections regardless of permissions.
; Default Values: user and group are set as the running user
;                 mode is set to 0660
listen.owner = nginx = nginx
;listen.mode = 0660

; The number of child processes to be created when pm is set to 'static' and the
; maximum number of child processes when pm is set to 'dynamic' or 'ondemand'.
; This value sets the limit on the number of simultaneous requests that will be
; served. Equivalent to the ApacheMaxClients directive with mpm_prefork.
; Equivalent to the PHP_FCGI_CHILDREN environment variable in the original PHP
; CGI. The below defaults are based on a server without much resources. Don't
; forget to tweak pm.* to fit your needs.
; Note: Used when pm is set to 'static', 'dynamic' or 'ondemand'
; Note: This value is mandatory.
pm.max_children = 20

Make the necessary changes to the configuration file: deny execution of any code on the server under the PHP process when loading the file and specify the time zone.

; cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI.  PHP's
; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok
; what PATH_INFO is.  For more information on PATH_INFO, see the cgi specs.  Setting
; this to 1 will cause PHP CGI to fix its paths to conform to the spec.  A setting
; of zero causes PHP to behave as before.  Default is 1.  You should fix your scripts

; Defines the default timezone used by the date functions
date.timezone = "Europe/Moscow"


In this example, the path is for PHP 7.4. Edit the path if you use a different version of PHP.

Start the PHP-FPM service:

/etc/init.d/php-fpm start

Add PHP-FPM to autostart:

rc-update add php-fpm

Example of Nginx configuration with PHP code

To provide PHP support, add the following to the configuration of the site running under Nginx. In the example below, Nginx exchanges information with the PHP process via a UNIX socket. In the server block, add the location block, which will contain the rules for working with PHP.

Apply the settings:

# localhost
server {
    listen 80;
    access_log /var/log/nginx/ main;
    error_log /var/log/nginx/ info;
    root /var/calculate/www/localhost/htdocs;
    location ~ \.php$ {
        # Check for non existing scripts or for error 404
        # Without this line, nginx will immediately send any requests ending with .php to php-fpm
        try_files $uri =404;
        include /etc/nginx/fastcgi.conf;
        fastcgi_pass unix:/run/php-fpm.socket;

Create a file and put the code for outputting information about PHP in it:

echo '<?php phpinfo(); ?>' > /var/calculate/www/localhost/htdocs/info.php

Edit access rights for all files in the root folder of the site:

chown -R nginx:nginx /var/calculate/www/localhost/htdocs

Add the corresponding entry to DNS. In the absence of DNS, you can add the entry to the static table of names of the computer from which the site will be accessed.

For Linux based systems, edit the list of domain names:


Check that Nginx has been configured correctly and re-read the file:

nginx -t && /etc/init.d/nginx reload


/etc/init.d/php-fpm start

Type in your browser. If everything is OK, you will see a page with complete info on PHP.