10 Comandos Nginx Mais Utilizados que Todo Usuário de Linux Deve Conhecer

Nginx (pronunciado Engine x) é um servidor proxy reverso gratuito, de código aberto, de alto desempenho, escalável, confiável, completo e popular para HTTP, um servidor proxy de e-mail e um servidor proxy genérico TCP/UDP.

Nginx é bem conhecido por sua configuração simples e baixo consumo de recursos devido ao seu alto desempenho, sendo utilizado para alimentar vários sites de alto tráfego na web, como GitHub, SoundCloud, Dropbox, Netflix, WordPress e muitos outros.

Leia também: 3 Hacks Úteis que Todo Usuário de Linux Deve Conhecer

Neste guia, explicaremos alguns dos comandos de gerenciamento de serviço Nginx mais comumente usados que, como desenvolvedor ou administrador de sistema, você deve ter à mão. Mostraremos comandos tanto para Systemd quanto para SysVinit.

Todas essas seguintes listas de comandos populares do Nginx devem ser executadas como um usuário root ou sudo e devem funcionar em qualquer distribuição Linux moderna, como CentOS, RHEL, Debian, Ubuntu e Fedora.

Instalar o Servidor Nginx

Para instalar o servidor web Nginx, use o gerenciador de pacotes padrão da sua distribuição, como mostrado.

$ sudo yum install epel-release && yum install nginx   [On CentOS/RHEL]
$ sudo dnf install nginx                               [On Fedora]
$ sudo apt install nginx                               [On Debian/Ubuntu]

Verificar a Versão do Nginx

Para verificar a versão do servidor web Nginx instalado no seu sistema Linux, execute o seguinte comando.

$ nginx -v

nginx version: nginx/1.12.2

O comando acima simplesmente exibe o número da versão. Se você deseja visualizar a versão e as opções de configuração, use a opção -V, como mostrado.

$ nginx -V
Show Nginx, Compiler and Configuration Parameters
nginx version: nginx/1.12.2
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/run/nginx.pid --lock-path=/run/lock/subsys/nginx --user=nginx --group=nginx --with-file-aio --with-ipv6 --with-http_auth_request_module --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --with-http_geoip_module=dynamic --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_slice_module --with-http_stub_status_module --with-http_perl_module=dynamic --with-mail=dynamic --with-mail_ssl_module --with-pcre --with-pcre-jit --with-stream=dynamic --with-stream_ssl_module --with-google_perftools_module --with-debug --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic' --with-ld-opt='-Wl,-z,relro -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -Wl,-E'

Verificar a Sintaxe da Configuração do Nginx

Antes de iniciar o serviço Nginx, você pode verificar se a sintaxe da sua configuração está correta. Isso é especialmente útil se você fez alterações ou adicionou uma nova configuração à estrutura de configuração existente.

Para testar a configuração do Nginx, execute o seguinte comando.

$ sudo nginx -t

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

Você pode testar a configuração do Nginx, exibi-la e sair usando a opção -T, como mostrado.

$ sudo nginx -T
Show Nginx Configuration Settings
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
# configuration file /etc/nginx/nginx.conf:
# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

....

Iniciar o Serviço Nginx

Para iniciar o serviço Nginx, execute o seguinte comando. Note que este processo pode falhar se a sintaxe de configuração não estiver OK.

$ sudo systemctl start nginx #systemd
OR
$ sudo service nginx start   #sysvinit

Ativar Serviço Nginx

O comando anterior apenas inicia o serviço temporariamente, para ativá-lo automaticamente na inicialização, execute o seguinte comando.

$ sudo systemctl enable nginx #systemd
OR
$ sudo service nginx enable   #sysv init

Reiniciar Serviço Nginx

Para reiniciar o serviço Nginx, uma ação que irá parar e depois iniciar o serviço.

$ sudo systemctl restart nginx #systemd
OR
$ sudo service nginx restart   #sysv init

Verificar Status do Serviço Nginx

Você pode verificar o status do serviço Nginx da seguinte forma. Este comando mostra informações de status em tempo de execução sobre o serviço.

$ sudo systemctl status nginx #systemd
OR
$ sudo service nginx status   #sysvinit
Show Nginx Status Information
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.
[root@tecmint ~]# systemctl status nginx
● nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
   Active: active (running) since Tue 2019-03-05 05:27:15 EST; 2min 59s ago
 Main PID: 31515 (nginx)
   CGroup: /system.slice/nginx.service
           ├─31515 nginx: master process /usr/sbin/nginx
           └─31516 nginx: worker process

Mar 05 05:27:15 tecmint.com systemd[1]: Starting The nginx HTTP and reverse proxy server...
Mar 05 05:27:15 tecmint.com nginx[31509]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
Mar 05 05:27:15 tecmint.com nginx[31509]: nginx: configuration file /etc/nginx/nginx.conf test is successful
Mar 05 05:27:15 tecmint.com systemd[1]: Failed to read PID from file /run/nginx.pid: Invalid argument
Mar 05 05:27:15 tecmint.com systemd[1]: Started The nginx HTTP and reverse proxy server.

Recarregar Serviço Nginx

Para instruir o Nginx a recarregar sua configuração, use o seguinte comando.

$ sudo systemctl reload nginx #systemd
OR
$ sudo service nginx reload   #sysvinit

Parar Serviço Nginx

Se você quiser parar o serviço Nginx por algum motivo, use o seguinte comando.

$ sudo systemctl stop nginx #systemd
OR
$ sudo service nginx stop   #sysvinit

Mostrar Ajuda de Comando Nginx

Para obter um guia de referência fácil de todos os comandos e opções do Nginx, use o seguinte comando.

$ systemctl -h nginx
Nginx Help Commands and Options
systemctl [OPTIONS...] {COMMAND} ...

Query or send control commands to the systemd manager.

  -h --help           Show this help
     --version        Show package version
     --system         Connect to system manager
  -H --host=[USER@]HOST
                      Operate on remote host
  -M --machine=CONTAINER
                      Operate on local container
  -t --type=TYPE      List units of a particular type
     --state=STATE    List units with particular LOAD or SUB or ACTIVE state
  -p --property=NAME  Show only properties by this name
  -a --all            Show all loaded units/properties, including dead/empty
                      ones. To list all units installed on the system, use
                      the 'list-unit-files' command instead.
  -l --full           Don't ellipsize unit names on output
  -r --recursive      Show unit list of host and local containers
     --reverse        Show reverse dependencies with 'list-dependencies'
     --job-mode=MODE  Specify how to deal with already queued jobs, when
                      queueing a new job
     --show-types     When showing sockets, explicitly show their type
  -i --ignore-inhibitors
...

Você também pode gostar de ler os seguintes artigos relacionados ao Nginx.

  1. O Guia Definitivo para Segurar, Reforçar e Melhorar o Desempenho do Servidor Web Nginx
  2. Amplify – Monitoramento NGINX Simplificado
  3. ngxtop – Monitorizar Arquivos de Log do Nginx em Tempo Real no Linux
  4. Como Instalar o Nginx com Hosts Virtuais e Certificado SSL
  5. Como Ocultar a Versão do Servidor Nginx no Linux

Isso é tudo por agora! Neste guia, explicamos alguns dos comandos de gerenciamento de serviço do Nginx mais comumente usados que você deve conhecer, incluindo iniciar, habilitar, reiniciar e parar o Nginx. Se você tiver alguma adição ou pergunta a fazer, use o formulário de feedback abaixo.

Source:
https://www.tecmint.com/useful-nginx-command-examples/