nginx beginner's guide
[[email protected] ~]# cd /opt/nginx1.6.0/
[[email protected] nginx1.6.0]# ll
total 36
drwx------ 2 nobody root 4096 Jul 18 20:25 client_body_temp
drwxr-xr-x 2 root root 4096 Jul 20 16:50 conf
drwx------ 2 nobody root 4096 Jul 18 20:25 fastcgi_temp
drwxr-xr-x 2 root root 4096 Jul 18 15:48 html
drwxr-xr-x 2 root root 4096 Jul 18 23:18 logs
drwx------ 6 nobody root 4096 Jul 18 23:43 proxy_temp
drwxr-xr-x 2 root root 4096 Jul 18 22:45 sbin
drwx------ 2 nobody root 4096 Jul 18 20:25 scgi_temp
drwx------ 2 nobody root 4096 Jul 18 20:25 uwsgi_temp
[[email protected] nginx1.6.0]# cd logs
[[email protected] logs]# ll
total 84
-rw-r--r-- 1 root root 69856 Jul 20 17:17 access.log
-rw-r--r-- 1 root root 708 Jul 20 16:50 error.log
-rw-r--r-- 1 root root 5 Jul 18 23:18 nginx.pid
[[email protected] logs]# cd ../conf/
[[email protected] conf]# ll
total 60
-rw-r--r-- 1 root root 1034 Jul 18 15:48 fastcgi.conf
-rw-r--r-- 1 root root 1034 Jul 18 22:43 fastcgi.conf.default
-rw-r--r-- 1 root root 964 Jul 18 15:48 fastcgi_params
-rw-r--r-- 1 root root 964 Jul 18 22:43 fastcgi_params.default
-rw-r--r-- 1 root root 2837 Jul 18 22:43 koi-utf
-rw-r--r-- 1 root root 2223 Jul 18 22:43 koi-win
-rw-r--r-- 1 root root 3957 Jul 18 15:48 mime.types
-rw-r--r-- 1 root root 3957 Jul 18 22:43 mime.types.default
-rw-r--r-- 1 root root 2765 Jul 20 16:50 nginx.conf
-rw-r--r-- 1 root root 2656 Jul 18 22:43 nginx.conf.default
-rw-r--r-- 1 root root 596 Jul 18 15:48 scgi_params
-rw-r--r-- 1 root root 596 Jul 18 22:43 scgi_params.default
-rw-r--r-- 1 root root 623 Jul 18 15:48 uwsgi_params
-rw-r--r-- 1 root root 623 Jul 18 22:43 uwsgi_params.default
-rw-r--r-- 1 root root 3610 Jul 18 22:43 win-utf
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.
Syntax: listen address[:port] [default_server] [ssl] [spdy] [proxy_protocol] [setfib=number] [fastopen=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [ipv6only=on|off] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
listen port [default_server] [ssl] [spdy] [proxy_protocol] [setfib=number] [fastopen=number] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [ipv6only=on|off] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
listen unix:path [default_server] [ssl] [spdy] [proxy_protocol] [backlog=number] [rcvbuf=size] [sndbuf=size] [accept_filter=filter] [deferred] [bind] [so_keepalive=on|off|[keepidle]:[keepintvl]:[keepcnt]];
Default:
listen *:80 | *:8000;
Context: server
linsten这个指令可以写在server context中.
Syntax: location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
Default: —
Context: server, location
user nobody; # a directive in the 'main' context
events {
# configuration of events
}
http {
# Configuration specific to HTTP and affecting all virtual servers
server {
# configuration of virtual server 1
location /one {
# configuration for processing URIs with '/one'
}
location /two {
# configuration for processing URIs with '/two'
}
}
server {
# configuration of virtual server 2
}
}
接下来说一下nginx的进程,
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).
nginx.conf 配置 :
#user nobody;
worker_processes 1;
[[email protected] conf]# ps -ewf|grep nginx
root 3222 1 0 Jul18 ? 00:00:00 nginx: master process nginx
nobody 28309 3222 0 16:50 ? 00:00:00 nginx: worker process
worker进程1个. 还有一个主进程.
nginx 主进程负责检查配置文件的正确性, 读取配置文件, 维护work进程(例如reload, stop等).
worker进程负责处理用户请求.
nginx进程管理, 启动, 重载配置文件, 停止.
nginx -h
nginx version: nginx/1.6.0
Usage: nginx [-?hvVtq] [-s signal] [-c filename] [-p prefix] [-g directives]
Options:
-?,-h : this help
-v : show version and exit
-V : show version and configure options then exit
-t : test configuration and exit
-q : suppress non-error messages during configuration testing
-s signal : send signal to a master process: stop, quit, reopen, reload
-p prefix : set prefix path (default: /opt/nginx1.6.0/)
-c filename : set configuration file (default: conf/nginx.conf)
-g directives : set global directives out of configuration file
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 直接关闭nginx
quit — graceful shutdown 拒绝新建请求, 同时处理完当前请求后关闭nginx
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.
或者直接给nginx进程发出信号, 例如QUIT信号, 相当于-s quit.
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.
nginx对信号的处理见
http://nginx.org/en/docs/control.html
nginx作为静态页面网站server的配置例子.
server {
listen 0.0.0.0:80;
2. 然后匹配server_name
server {
listen 0.0.0.0:80;
server_name dba.sky-mobi.com;
因为同一个nginx可以配置同样的监听, 不同的server_name, 来为多个域名服务. 例如 :
server {
listen 0.0.0.0:80;
server_name dba.sky-mobi.com;
...
}
server {
listen 0.0.0.0:80;
server_name www.sky-mobi.com default_server;
...
Syntax: location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
Default: —
Context: server, location
A location can either be defined by a prefix string, or by a regular expression. Regular expressions are specified with the preceding “~*” modifier (for case-insensitive matching), or the “~” modifier (for case-sensitive matching).
Higher priority is given to regular expressions, unless the “^~” modifier is used. Among the prefix strings NGINX selects the most specific one (that is, the longest and most complete string). The exact logic for selecting a location to process a request is given below:
1. Test the URI against all prefix strings.
2. The “=” modifier defines an exact match of the URI and a prefix string. If the exact match is found, the search stops.
3. If the “^~” modifier prepends the longest matching prefix string, the regular expressions are not checked.
4. Store the longest matching prefix string.
5. Start testing the URI against regular expressions.
6. Break on the first matching regular expression and use the corresponding location.
7. If no regular expression matches, use the location corresponding to the stored prefix string.
A typical example of using the “=” modifier is with the usage of “/”. If the “/” request needs to be served often, specifying the location parameter as “= /” will speed up processing of these requests. As noted above, this is due to the search being stopped after the first comparison.
In most cases, a context that is defined inside another context will inherits its directives. When that happens, and you then declare the the same directive on the current level, the directive on the current level will override the inherited one. For more information on context inheritence see the proxy_set_header documentation.
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.
Syntax: proxy_pass URL;
Default: —
Context: location, if in location, limit_except
Sets the protocol and address of a proxied server and an optional URI to which a location should be mapped. As a protocol, “http” or “https” can be specified. The address can be specified as a domain name or IP address, and an optional port:
proxy_pass http://localhost:8000/uri/;
or as a UNIX-domain socket path specified after the word “unix” and enclosed in colons:
proxy_pass http://unix:/tmp/backend.socket:/uri/;
If a domain name resolves to several addresses, all of them will be used in a round-robin fashion. In addition, an address can be specified as a server group.
A request URI is passed to the server as follows:
If the proxy_pass directive is specified with a URI, then when a request is passed to the server, the part of a normalizedrequest URI matching the location is replaced by a URI specified in the directive:
location /name/ {
proxy_pass http://127.0.0.1/remote/;
}
If proxy_pass is specified without a URI, the request URI is passed to the server in the same form as sent by a client when the original request is processed, or the full normalized request URI is passed when processing the changed URI:
location /some/path/ {
proxy_pass http://127.0.0.1;
}
Before version 1.1.12, if proxy_pass is specified without a URI, the original request URI might be passed instead of the changed URI in some cases.
In some cases, the part of a request URI to be replaced cannot be determined:
When location is specified using a regular expression.
In this case, the directive should be specified without a URI.
When the URI is changed inside a proxied location using the rewrite directive, and this same configuration will be used to process a request (break):
location /name/ {
rewrite /name/([^/]+) /users?name=$1 break;
proxy_pass http://127.0.0.1;
}
In this case, the URI specified in the directive is ignored and the full changed request URI is passed to the server.
A server name, its port and the passed URI can also be specified using variables:
proxy_pass http://$host$uri;
or even like this:
proxy_pass $request;
In this case, the server name is searched among the described server groups, and, if not found, is determined using a resolver.
WebSocket proxying requires special configuration and is supported since version 1.3.13.
server {
listen 8080;
root /data/up1;
location / {
}
}
server {
location / {
proxy_pass http://localhost:8080/;
}
location ~ \.(gif|jpg|png)$ {
root /data/images;
}
}
location / {
proxy_pass http://localhost:8080/;
}
作为代理, 请求转发给http://localhost:8080/
http://localhost:8080/xxx/xx....
也就是
server {
listen 8080;
root /data/up1;
location / {
}
}
location ~ \.(gif|jpg|png)$ {
root /data/images;
}
Syntax: |
fastcgi_pass |
---|---|
Default: | — |
Context: |
location , if in location |
Sets the address of a FastCGI server. The address can be specified as a domain name or IP address, and an optional port:
fastcgi_pass localhost:9000;
or as a UNIX-domain socket path:
fastcgi_pass unix:/tmp/fastcgi.socket;
If a domain name resolves to several addresses, all of them will be used in a round-robin fashion. In addition, an address can be specified as a server group.
Syntax: |
fastcgi_param |
---|---|
Default: | — |
Context: |
http , server , location |
Sets a parameter
that should be passed to the FastCGI server. The value
can contain text, variables, and their combination. These directives are inherited from the previous level if and only if there are no fastcgi_param
directives defined on the current level.
The following example shows the minimum required settings for PHP:
fastcgi_param SCRIPT_FILENAME /home/www/scripts/php$fastcgi_script_name; fastcgi_param QUERY_STRING $query_string;
The SCRIPT_FILENAME
parameter is used in PHP for determining the script name, and the QUERY_STRING
parameter is used to pass request parameters.
For scripts that process POST
requests, the following three parameters are also required:
fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length;
If PHP was built with the --enable-force-cgi-redirect
configuration parameter, the REDIRECT_STATUS
parameter should also be passed with the value “200”:
fastcgi_param REDIRECT_STATUS 200;
If a directive is specified with if_not_empty
(1.1.11) then such a parameter will not be passed to the server until its value is not empty:
fastcgi_param HTTPS $https if_not_empty;
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.
还有一个例子, 以.php结尾的文件交给fastcgi处理, 例如php-fpm :
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
推荐阅读
-
nginx beginner's guide
-
WPF: A Beginner's Guide: Part 2 of n
-
读书笔记- the data engineer's guide to spark
-
《Linux DRM Developer's Guide》学习笔记--内存管理
-
How to Add a Shortcode in WordPress? (Beginner’s Guide
-
nginx--Beginner's Guide
-
A Beginner‘s Guide to JavaScript‘s Prototype
-
Nginx 入门手册 (Beginner’s Guide)
-
k8s中负载均衡器【ingress-nginx】部署
-
使用Let's Encrypt + Nginx生成免费HTTPS证书