Как найти файл конфигурации nginx

This guide gives a basic introduction to nginx and describes some
simple tasks that can be done with it.
It is supposed that nginx is already installed on the reader’s machine.
If it is not, see the Installing nginx page.
This guide describes how to start and stop nginx, and reload its
configuration, explains the structure
of the configuration file and describes how to set up nginx
to serve out static content, how to configure nginx as a proxy
server, and how to connect it with a FastCGI application.

nginx has one master process and several worker processes.
The main purpose of the master process is to read and evaluate configuration,
and maintain worker processes.
Worker processes do actual processing of requests.
nginx employs event-based model and OS-dependent mechanisms to efficiently
distribute requests among worker processes.
The number of worker processes is defined in the configuration file and
may be fixed for a given configuration or automatically adjusted to the
number of available CPU cores (see
worker_processes).

The way nginx and its modules work is determined in the configuration file.
By default, the configuration file is named nginx.conf
and placed in the directory
/usr/local/nginx/conf,
/etc/nginx, or
/usr/local/etc/nginx.

Starting, Stopping, and Reloading Configuration

To start nginx, run the executable file.
Once nginx is started, it can be controlled by invoking the executable
with the -s parameter.
Use the following syntax:

nginx -s signal

Where signal may be one of the following:

  • stop — fast shutdown
  • quit — graceful shutdown
  • reload — reloading the configuration file
  • reopen — reopening the log files

For example, to stop nginx processes with waiting for the worker processes
to finish serving current requests, the following command can be executed:

nginx -s quit

This command should be executed under the same user that
started nginx.

Changes made in the configuration file
will not be applied until the command to reload configuration is
sent to nginx or it is restarted.
To reload configuration, execute:

nginx -s reload

Once the master process receives the signal to reload configuration,
it checks the syntax validity
of the new configuration file and tries to apply the configuration provided
in it.
If this is a success, the master process starts new worker processes
and sends messages to old worker processes, requesting them to
shut down.
Otherwise, the master process rolls back the changes and
continues to work with the old configuration.
Old worker processes, receiving a command to shut down,
stop accepting new connections and continue to service current requests until
all such requests are serviced.
After that, the old worker processes exit.

A signal may also be sent to nginx processes with the help of Unix tools
such as the kill utility.
In this case a signal is sent directly to a process with a given process ID.
The process ID of the nginx master process is written, by default, to the
nginx.pid in the directory
/usr/local/nginx/logs or
/var/run.
For example, if the master process ID is 1628, to send the QUIT signal
resulting in nginx’s graceful shutdown, execute:

kill -s QUIT 1628

For getting the list of all running nginx processes, the ps
utility may be used, for example, in the following way:

ps -ax | grep nginx

For more information on sending signals to nginx, see
Controlling nginx.

Configuration File’s Structure

nginx consists of modules which are controlled by directives specified
in the configuration file.
Directives are divided into simple directives and block directives.
A simple directive consists of the name and parameters separated by spaces
and ends with a semicolon (;).
A block directive has the same structure as a simple directive, but
instead of the semicolon it ends with a set of additional instructions
surrounded by braces ({ and }).
If a block directive can have other directives inside braces,
it is called a context (examples:
events,
http,
server,
and
location).

Directives placed in the configuration file outside
of any contexts are considered to be in the
main context.
The events and http directives
reside in the main context, server
in http, and location in
server.

The rest of a line after the # sign is considered a comment.

Serving Static Content

An important web server task is serving out
files (such as images or static HTML pages).
You will implement an example where, depending on the request,
files will be served from different local directories: /data/www
(which may contain HTML files) and /data/images
(containing images).
This will require editing of the configuration file and setting up of a
server
block inside the http
block with two location
blocks.

First, create the /data/www directory and put an
index.html file with any text content into it and
create the /data/images directory and place some
images in it.

Next, open the configuration file.
The default configuration file already includes several examples of
the server block, mostly commented out.
For now comment out all such blocks and start a new
server block:

http {
    server {
    }
}

Generally, the configuration file may include several
server blocks
distinguished by ports on which
they listen to
and by
server names.
Once nginx decides which server processes a request,
it tests the URI specified in the request’s header against the parameters of the
location directives defined inside the
server block.

Add the following location block to the
server block:

location / {
    root /data/www;
}

This location block specifies the
/” prefix compared with the URI from the request.
For matching requests, the URI will be added to the path specified in the
root
directive, that is, to /data/www,
to form the path to the requested file on the local file system.
If there are several matching location blocks nginx
selects the one with the longest prefix.
The location block above provides the shortest
prefix, of length one,
and so only if all other location
blocks fail to provide a match, this block will be used.

Next, add the second location block:

location /images/ {
    root /data;
}

It will be a match for requests starting with /images/
(location / also matches such requests,
but has shorter prefix).

The resulting configuration of the server block should
look like this:

server {
    location / {
        root /data/www;
    }

    location /images/ {
        root /data;
    }
}

This is already a working configuration of a server that listens
on the standard port 80 and is accessible on the local machine at
http://localhost/.
In response to requests with URIs starting with /images/,
the server will send files from the /data/images directory.
For example, in response to the
http://localhost/images/example.png request nginx will
send the /data/images/example.png file.
If such file does not exist, nginx will send a response
indicating the 404 error.
Requests with URIs not starting with /images/ will be
mapped onto the /data/www directory.
For example, in response to the
http://localhost/some/example.html request nginx will
send the /data/www/some/example.html file.

To apply the new configuration, start nginx if it is not yet started or
send the reload signal to the nginx’s master process,
by executing:

nginx -s reload

In case something does not work as expected, you may try to find out
the reason in access.log and
error.log files in the directory
/usr/local/nginx/logs or
/var/log/nginx.

Setting Up a Simple Proxy Server

One of the frequent uses of nginx is setting it up as a proxy server, which
means a server that receives requests, passes them to the proxied servers,
retrieves responses from them, and sends them to the clients.

We will configure a basic proxy server, which serves requests of
images with files from the local directory and sends all other requests to a
proxied server.
In this example, both servers will be defined on a single nginx instance.

First, define the proxied server by adding one more server
block to the nginx’s configuration file with the following contents:

server {
    listen 8080;
    root /data/up1;

    location / {
    }
}

This will be a simple server that listens on the port 8080
(previously, the listen directive has not been specified
since the standard port 80 was used) and maps
all requests to the /data/up1 directory on the local
file system.
Create this directory and put the index.html file into it.
Note that the root directive is placed in the
server context.
Such root directive is used when the
location block selected for serving a request does not
include its own root directive.

Next, use the server configuration from the previous section
and modify it to make it a proxy server configuration.
In the first location block, put the
proxy_pass
directive with the protocol, name and port of the proxied server specified
in the parameter (in our case, it is http://localhost:8080):

server {
    location / {
        proxy_pass http://localhost:8080;
    }

    location /images/ {
        root /data;
    }
}

We will modify the second location
block, which currently maps requests with the /images/
prefix to the files under the /data/images directory,
to make it match the requests of images with typical file extensions.
The modified location block looks like this:

location ~ .(gif|jpg|png)$ {
    root /data/images;
}

The parameter is a regular expression matching all URIs ending
with .gif, .jpg, or .png.
A regular expression should be preceded with ~.
The corresponding requests will be mapped to the /data/images
directory.

When nginx selects a location block to serve a request
it first checks location
directives that specify prefixes, remembering location
with the longest prefix, and then checks regular expressions.
If there is a match with a regular expression, nginx picks this
location or, otherwise, it picks the one remembered earlier.

The resulting configuration of a proxy server will look like this:

server {
    location / {
        proxy_pass http://localhost:8080/;
    }

    location ~ .(gif|jpg|png)$ {
        root /data/images;
    }
}

This server will filter requests ending with .gif,
.jpg, or .png
and map them to the /data/images directory (by adding URI to the
root directive’s parameter) and pass all other requests
to the proxied server configured above.

To apply new configuration, send the reload signal to
nginx as described in the previous sections.

There are many more
directives that may be used to further configure a proxy connection.

Setting Up FastCGI Proxying

nginx can be used to route requests to FastCGI servers which run
applications built with various frameworks and programming languages
such as PHP.

The most basic nginx configuration to work with a FastCGI server
includes using the
fastcgi_pass
directive instead of the proxy_pass directive,
and fastcgi_param
directives to set parameters passed to a FastCGI server.
Suppose the FastCGI server is accessible on localhost:9000.
Taking the proxy configuration from the previous section as a basis,
replace the proxy_pass directive with the
fastcgi_pass directive and change the parameter to
localhost:9000.
In PHP, the SCRIPT_FILENAME parameter is used for
determining the script name, and the QUERY_STRING
parameter is used to pass request parameters.
The resulting configuration would be:

server {
    location / {
        fastcgi_pass  localhost:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param QUERY_STRING    $query_string;
    }

    location ~ .(gif|jpg|png)$ {
        root /data/images;
    }
}

This will set up a server that will route all requests except for
requests for static images to the proxied server operating on
localhost:9000 through the FastCGI protocol.

Understand the basic elements in an NGINX or NGINX Plus configuration file, including directives and contexts.

NGINX and NGINX Plus are similar to other services in that they use a text‑based configuration file written in a particular format. By default the file is named nginx.conf and for NGINX Plus is placed in the /etc/nginx directory. (For NGINX Open Source , the location depends on the package system used to install NGINX and the operating system. It is typically one of /usr/local/nginx/conf, /etc/nginx, or /usr/local/etc/nginx.)

Directives

The configuration file consists of directives and their parameters. Simple (single‑line) directives each end with a semicolon. Other directives act as “containers” that group together related directives, enclosing them in curly braces ( {} ); these are often referred to as blocks. Here are some examples of simple directives.

user             nobody;
error_log        logs/error.log notice;
worker_processes 1;

Feature-Specific Configuration Files

To make the configuration easier to maintain, we recommend that you split it into a set of feature‑specific files stored in the /etc/nginx/conf.d directory and use the include directive in the main nginx.conf file to reference the contents of the feature‑specific files.

include conf.d/http;
include conf.d/stream;
include conf.d/exchange-enhanced;

Contexts

A few top‑level directives, referred to as contexts, group together the directives that apply to different traffic types:

  • events – General connection processing
  • http – HTTP traffic
  • mail – Mail traffic
  • stream – TCP and UDP traffic

Directives placed outside of these contexts are said to be in the main context.

Virtual Servers

In each of the traffic‑handling contexts, you include one or more server blocks to define virtual servers that control the processing of requests. The directives you can include within a server context vary depending on the traffic type.

For HTTP traffic (the http context), each server directive controls the processing of requests for resources at particular domains or IP addresses. One or more location contexts in a server context define how to process specific sets of URIs.

For mail and TCP/UDP traffic (the mail and stream contexts) the server directives each control the processing of traffic arriving at a particular TCP port or UNIX socket.

Sample Configuration File with Multiple Contexts

The following configuration illustrates the use of contexts.

user nobody; # a directive in the 'main' context

events {
    # configuration of connection processing
}

http {
    # Configuration specific to HTTP and affecting all virtual servers  

    server {
        # configuration of HTTP virtual server 1       
        location /one {
            # configuration for processing URIs starting with '/one'
        }
        location /two {
            # configuration for processing URIs starting with '/two'
        }
    } 
    
    server {
        # configuration of HTTP virtual server 2
    }
}

stream {
    # Configuration specific to TCP/UDP and affecting all virtual servers
    server {
        # configuration of TCP virtual server 1 
    }
}

Inheritance

In general, a child context – one contained within another context (its parent) – inherits the settings of directives included at the parent level. Some directives can appear in multiple contexts, in which case you can override the setting inherited from the parent by including the directive in the child context. For an example, see the proxy_set_header directive.

Reloading Configuration

For changes to the configuration file to take effect, it must be reloaded. You can either restart the nginx process or send the reload signal to upgrade the configuration without interrupting the processing of current requests. For details, see Controlling NGINX Processes at Runtime.

With NGINX Plus, you can dynamically reconfigure load balancing across the servers in an upstream group without reloading the configuration. You can also use the NGINX Plus API and key‑value store to dynamically control access, for example based on client IP address.


In this article I will tell you where Nginx server is installed and how to find out it’s configuration file after installation. It is very useful when you jump into an existing Nginx server and just want to find and modify it’s configuration files.

1. How To Find Nginx Install Path And Configuration Files.

There are several commands that you can use to find Nginx installation path and it’s configuration files path.

  1. Open a terminal and run whereis nginx command to return where the Nginx binary file is. But the Nginx bin directory path should exist in PATH system environment.
    $ whereis nginx
    nginx: /usr/bin/nginx /usr/local/nginx
    
    $ echo $PATH
    /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
  2. If there are multiple Nginx binary file path records in above command result, you can run which nginx to show the currently used Nginx binary file path.
    $ which nginx
    /usr/bin/nginx
  3. You can run command ls -al /usr/bin/nginx to get the Nginx binary file linked real Nginx server binary file as below.
    $ ls -al /usr/bin/nginx 
    lrwxrwxrwx. 1 root root 28 Dec 21 08:30 /usr/bin/nginx -> /www/server/nginx/sbin/nginx
  4. If the Nginx binary file path do not exist in environment variable PATH value, you can run ps -ef | grep nginx command to list currently running Nginx process information.
    $ ps -ef|grep nginx
    root      1412     1  0 Dec21 ?        00:00:00 nginx: master process /www/server/nginx/sbin/nginx -c /www/server/nginx/conf/nginx.conf
  5. From above ps -ef|grep nginx command, we can see Nginx binary file is  located at /www/server/nginx/sbin/nginx, and Nginx configuration file is located at /www/server/nginx/conf/nginx.conf.
  6. If the Nginx server is running now, you can also run command nginx -t to get and test the Nginx server configuration file.
    $ nginx -t
    nginx: the configuration file /www/server/nginx/conf/nginx.conf syntax is ok
    nginx: configuration file /www/server/nginx/conf/nginx.conf test is successful

2. Some Nginx Useful Commands.

  1. Command nginx -V/v can get current executing Nginx server version. The -V will return more detail version information.
    $ nginx -V
    nginx version: nginx/1.18.0
    built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) 
    built with OpenSSL 1.1.1i  8 Dec 2020
    ..............
    
    $ nginx -v
    nginx version: nginx/1.18.0
  2. Start / stop / restart / reload Nginx server.
    $ sudo systemctl start nginx
    
    $ sudo systemctl stop nginx
    
    $ sudo systemctl restart nginx
    
    $ sudo systemctl reload nginx
    
  3. Get Nginx running status.
    $ sudo systemctl status nginx
  4. Enable / Disable launch Nginx server when Linux server is started.
    $ sudo systemctl enable nginx
    
    $ sudo systemctl disable nginx
  5. Display Nginx command line help information.
    $ sudo systemctl -h nginx
    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
    .........
    .........

Working on a client’s server where there are two different versions of nginx installed. I think one of them was installed with the brew package manager (its an osx box) and the other seems to have been compiled and installed with the nginx packaged Makefile. I searched for all of the nginx.conf files on the server, but none of these files define the parameters that nginx is actually using when I start it on the server. Where is the nginx.conf file that I’m unaware of?

Daniel Li's user avatar

Daniel Li

14.9k6 gold badges42 silver badges60 bronze badges

asked Nov 11, 2013 at 15:33

rgb's user avatar

Running nginx -t through your commandline will issue out a test and append the output with the filepath to the configuration file (with either an error or success message).

answered Nov 11, 2013 at 15:38

Daniel Li's user avatar

Daniel LiDaniel Li

14.9k6 gold badges42 silver badges60 bronze badges

0

Both nginx -t and nginx -V would print out the default nginx config file path.

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

$ nginx -V
nginx version: nginx/1.11.1
built by gcc 4.9.2 (Debian 4.9.2-10)
built with OpenSSL 1.0.1k 8 Jan 2015
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf ...

If you want, you can get the config file by:

$ nginx -V 2>&1 | grep -o '--conf-path=(.*conf)' | cut -d '=' -f2
/etc/nginx/nginx.conf

Even if you have loaded some other config file, they would still print out the default value.


ps aux would show you the current loaded nginx config file.

$ ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root        11  0.0  0.2  31720  2212 ?        Ss   Jul23   0:00 nginx: master process nginx -c /app/nginx.conf

So that you could actually get the config file by for example:

$ ps aux | grep "[c]onf" | awk '{print $(NF)}'
/app/nginx.conf

answered Jul 24, 2016 at 0:25

Jing Li's user avatar

Jing LiJing Li

14.4k7 gold badges57 silver badges68 bronze badges

0

% ps -o args -C nginx
COMMAND
build/sbin/nginx -c ../test.conf

If nginx was run without the -c option, then you can use the -V option to find out the configure arguments that were set to non-standard values. Among them the most interesting for you are:

--prefix=PATH                      set installation prefix
--sbin-path=PATH                   set nginx binary pathname
--conf-path=PATH                   set nginx.conf pathname

Daniel Li's user avatar

Daniel Li

14.9k6 gold badges42 silver badges60 bronze badges

answered Nov 11, 2013 at 17:02

VBart's user avatar

VBartVBart

14.6k4 gold badges45 silver badges49 bronze badges

1

which nginx

will give you the path of the nginx being used


EDIT (2017-Jan-18)

Thanks to Will Palmer’s comment on this answer, I have added the following…

If you’ve installed nginx via a package manager such as HomeBrew…

which nginx

may not give you the EXACT path to the nginx being used. You can however find it using

realpath $(which nginx)

and as mentioned by @Daniel Li

you can get configuration of nginx via his method

alternatively you can use this:

nginx -V

answered Apr 14, 2016 at 21:01

Craig Wayne's user avatar

Craig WayneCraig Wayne

4,3403 gold badges35 silver badges48 bronze badges

3

All other answers are useful but they may not help you in case nginx is not on PATH so you’re getting command not found when trying to run nginx:

I have nginx 1.2.1 on Debian 7 Wheezy, the nginx executable is not on PATH, so I needed to locate it first. It was already running, so using ps aux | grep nginx I have found out that it’s located on /usr/sbin/nginx, therefore I needed to run /usr/sbin/nginx -t.

If you want to use a non-default configuration file (i.e. not /etc/nginx/nginx.conf), run it with the -c parameter: /usr/sbin/nginx -c <path-to-configuration> -t.

You may also need to run it as root, otherwise nginx may not have permissions to open for example logs, so the command would fail.

answered Feb 15, 2019 at 18:05

David Ferenczy Rogožan's user avatar

Path of nginx.conf in MacOS

/usr/local/etc/nginx/nginx.conf

Mark Rotteveel's user avatar

answered Apr 22, 2022 at 11:23

Aakash Handa's user avatar

Aakash HandaAakash Handa

1,18510 silver badges18 bronze badges

In addition to @Daniel Li’s answer, the nginx installation with Valet would use the Velet configuration as well; this is found in /usr/local/etc/nginx/valet/valet.conf. The nginx.conf file would have imported this Valet conf file.

The settings you need may be in the Valet file.

J. Scott Elblein's user avatar

answered Oct 24, 2017 at 12:29

Olusola Omosola's user avatar

Let’s save a time

you can find your nginx.conf file or any file using mlocate

$ mlocate <any file name or extention>

$ mlocate nginx.conf

If mlocate package not installed or ERROR: mlocate has no installation candidate

So you should proceed as follows:

$ sudo apt update

$ sudo apt install mlocate

or

$ sudo apt-get update

$ sudo apt-get install mlocate

Hopefully, your issue should be handled.

answered Jan 23 at 8:57

CHAVDA MEET's user avatar

CHAVDA MEETCHAVDA MEET

7498 silver badges14 bronze badges

for me

$ nginx -t                              
nginx: the configuration file /opt/homebrew/etc/nginx/nginx.conf syntax is ok
nginx: configuration file /opt/homebrew/etc/nginx/nginx.conf test is successful

$ vim /opt/homebrew/etc/nginx/nginx.conf

answered May 26 at 8:20

tuwilof's user avatar

tuwiloftuwilof

3313 silver badges6 bronze badges

Хотел внести некоторые поправки в файл конфигурации nginx домена, но не обнаружил его в ispmanager:
4baeda6784554e00ae832c0cdebbed7a.png
хотя на другом сервере он есть:
f4186b205d9944488ceb06b903b276f4.png

Подскажите как найти этот файл, по адресам /etc/nginx/vhosts/, /etc/nginx/sites-available/ нету.
CentOS-7, ISPmanager Lite 5.84.1


  • Вопрос задан

    более трёх лет назад

  • 14755 просмотров

Попробуйте проверить вообще nginx установлен или нет (вполне возможно Вы работаете под апачем), если установлен, то в /etc/nginx/sites-available/ создайте любой файл, доступный пользователю nginx’а (прописан в /etc/nginx/nginx.conf в самом верху) и запишите в этот файл всю конфигурацию и поставьте симлинк на этот файл в /etc/nginx/sites-enabled/

Пригласить эксперта


  • Показать ещё
    Загружается…

Сбер

Нижний Новгород

от 170 500 ₽

29 мая 2023, в 16:15

10000 руб./за проект

29 мая 2023, в 15:27

1800 руб./за проект

29 мая 2023, в 15:00

5000 руб./за проект

Минуточку внимания

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Межкомнатная дверь поцарапалась как исправить
  • Как составить письмо по ветхому жилью
  • Вчера играла на радио как найти
  • Как найти битое письмо
  • Как найти синус бета зная синус альфа

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии