Nginx from getting started to mastering "(2nd (Total 3 sections)"

Source: Internet
Author: User


    1. The configuration used by Nginx as a Web server.

    2. Network connection-related configurations:


The configuration used by Nginx as a Web server.

1. HTTP configuration section:

syntax:http {...}

http{}: Introduced by the Ngx_http_core_module module;


2. Server configuration section:

Syntax:server {...}

server{}: Introduced by the Ngx_http_core_module module;


3. Location configuration section:

syntax:location [= | ~ | ~* | ^~] URI {...}
Location @name {...}
Context:server, location

location{}: Introduced by the Ngx_http_core_module module;

4. Configure the framework:

http {     upstream {           ...  }      server {              location {                       root  "/path/to/ Somedir ";                    ...            } #  Similar to <location&gt in httpd, which defines a mapping between a URL and a local file system;           Multiple location;         location url {  can be specified within a server                       if ... {                              ...                      }               }       }  #  each server is similar to the one in httpd <VirtualHost>;           server {                ...       }


    1. HTTP-HTTP-related directives can only be placed in HTTP, server, location, upstream, if contexts, but some directives are only applied to some of these 5 contexts;

    2. To differentiate and facilitate the management of each server segment, the common "include file_path" reference;


HTTP {... include server.conf;//This configuration file server.conf uses a relative path, relative to the root path/usr/local/nginx;}

3. Configuration directives:

1) server {};
Function: Define a virtual host;

server {listen 8080;      server_name; Root "/web/html"; }

2) Listen

Function: Specifies the address and port of the listener;

Listen address[:P ort]listen PORT;

3) server_name name [...];
Function: Can be followed by more than one host, the name can also use regular expressions (~) or wildcard characters: (~ start)
Matching rules:
(1) Do a precise matching check first;
(2) left wildcard match check: *
(3) Right wildcard match check: such as mail.*
(4) Regular expression matching check: such as ~^.*\.yangbin\.com$
(5) Default_server;

server {server_name;}    server {server_name *;} server {server_name mail.*;}

4) root path;
Function: Sets the resource path mapping, which indicates the starting path on the file system where the requested URL corresponds to the resource;
The larger the placement range, the smaller the effective range;

5) Location [= | ~ | ~* | ^~] URI {...}
Location @name {...}
Function: Allows to match the defined location according to the URL requested by the user, and when matched, the request will be processed by the configuration in the corresponding location configuration block, such as access control functions;

Matching rules:
1) =: exact matching check;
2) ~: Regular expression pattern matching check, character case-sensitive;
3) ~*: Regular expression module matching check, do not distinguish between character casing;
4) ^~: The first half of the URI matches, and the regular expression is not supported;

Matching priority: Exact match (=), ^~,~,~*, location without any symbols; That is, match the normal, then match the regular;

server {        listen 80;         server_name;          location / {            root  "/Web/ Html/";              index index.html  index.htm;        }         location /images/ {             root  "/web/images/",          }  //the above two lines actually represent the full path is/ web/images/images            //directory name must be added after "/" .         location ~* \.php$ {             fcgipass;         } } 

Such as:

/web/images There is a xx.png, visit: Http:// can be, pay attention to the first part of the area separate.
Error to view the corresponding error log and access log;

6) alias Path;

Function: For location configuration segment, define path alias;

location/images/{root "/web/web1";} location/images/{alias "/www/pictures";}//Here access to/images/xx.html is the/www/pictures/xx.html of the visit.


Root indicates that the path is the corresponding location "/" URL;
Alias represents a path mapping, where the URL defined after the location directive is relative to the path indicated by alias;
In general, it is a good practice to configure alias in Location/other by configuring root in Location/.

one. location ~ ^/awstats/ {        alias /Web/   }    Visit:      actually visited is first. location ~ ^/awstats/ {                               #使用alias时目录名后面一定要加 "/"         alias /Web/awstats/;   }    Visit:      actually visited is third. location ~ ^/awstats/  {       root /web/;   }    Access:/http     actually accesses the

7) index file;
Function: Set the default main page face;

Index index.php index.html;

8) Error_page code [...] [=code] URI | @name
Function: Specify the specific error page according to the HTTP response status code;

Error_page 404/404_customed.html; That is, the 404 error page is set to our own designated page;

[=code]: In response to the indicated response code, rather than the default original response, by default, the response code of the new resource is its response code;
Example: Configuring in the server segment

server{... fastcgi_intercept_errors on;  Error_page 404/309.html;    The/309.html here is relative to the root directory of the Web site, that is, the location/corresponding root path.    Location/{root "/web/www"; }}[[email protected] nginx]# ls/web/www/309.html index.html[[email protected] nginx]#

Syntax: Fastcgi_intercept_errors on|off
Default value: Fastcgi_intercept_errors off
Using fields: HTTP, server, location
This directive specifies whether to pass 4xx and 5xx error messages to the client, or to allow Nginx to handle error messages using Error_page.
You must explicitly specify the processing method in Error_page to make this parameter valid.

9) IP-based access control:
Allow Ip/network;
Deny Ip/network;


location/js/{root/web/www/;     Allow; Deny all; }

10) User-based access control

Syntax: Auth_basic STRING | Off
Default value: Auth_basic off;
Configuration segment: HTTP, server, location, limit_except

By default, authentication is not turned on, and the characters are displayed in the popup window if they are followed by characters.

Syntax: Auth_basic_user_file "/path/to/password_file";
Default value:-
Configuration segment: HTTP, server, location, limit_except

Relative paths can be used. The account password file is recommended to use HTPASSWD to create;

HTPASSWD command required to install Apache HTTPD service obtained.


[[email protected] nginx]# which htpasswd/usr/bin/ Htpasswd [[email protected] nginx]# htpasswd --help [[email protected]  nginx]# id yangbinuid=1000 (Yangbin)  gid=1000 (yangbin)   Group =1000 (Yangbin) [[email  protected] nginx]# htpasswd -cm  conf/htpasswd/.htpasswd yangbinnew  password: re-type new password: adding password for user yangbin[[ Total dosage of email protected] nginx]# ll ./htpasswd/ -a  4drwxr-xr-x.  2  Root root  23 1 Month   12 16:07 .drwxr-xr-x. 13 root root  182 1 month   12 16:06  -rw-r--r--.   1 root root  46 1 Month   12 16:07 .htpasswd[[ EMAIL&NBSP;PROTECTED]&NBSP;NGINX]#&NBSP;CHOWN&NBSP;NGINX:ROOT&NBSP;./HTPASSWD/.HTPASSWD 
[Email protected] nginx]# Vim conf/server.conf ... location/images/{alias/web/images/;            Auth_basic Input_password;  Auth_basic_user_file htpasswd/.htpasswd; }  ... [Email protected] nginx]#/sbin/nginx-s Reload

Browser access:

650) this.width=650; "src=" Https:// "title=" Htpasswd01. PNG "alt=" Wkiom1h3prxibbg3aaa31ozoacw659.png "/>


One) HTTPS service
Implementation method: Generate the private key, generate a certificate signing request, and obtain a certificate;

server {listen 443 SSL;         server_name localhost;     SSL_CERTIFICATE/USR/LOCAL/NGINX/SSL/NGINX.CRT;         Ssl_certificate_key/usr/local/nginx/ssl/nginx.key;     Ssl_session_cache shared:ssl:1m;         Ssl_session_timeout 5m; Ssl_ciphers high:!anull:!     MD5; Ssl_prefer_server_ciphers on; }

HTTPS specific configuration process, I in LVS that a blog has written, here no longer repeat.

Stub_status {On|off}
The context is used only in the location : context;
Function: Mainly used to view some status information of Nginx.
This module is not compiled into Nginx by default, if you want to use the module, you need to compile the installation Nginx specified:


[Email protected] nginx-1.10.2]# Pwd/mnt/tools/nginx-1.10.2[[email protected] nginx-1.10.2]#./configure--help | Egrep "stub"--with-http_stub_status_module enable Ngx_http_stub_status_module[[email protected] nginx-1.10.2]#./con Figure–with-http_stub_status_module

To see if an installed Nginx contains a "stub_status" module:


Examples of results:

server {Listen 80;              server_name;           Location/{root "/web/www";       Stub_status on; }}
[Email protected] ~]# Curl Connections:6server accepts handled requests 241 241 431 reading:0 Writi Ng:1 waiting:0 [[email protected] ~]#


(1) Active Connections:6 # Current number of connections in open state;
(2) server accepts handled requests
(3) 241 241 431
241 number of connections that have been received
241 number of connections that have been processed
431 number of requests processed: in "Stay Connected" mode, the number of requests may be more than the number of connections;
(4) reading:0 writing:1 Waiting:5
Reading: The number of connections that are in the receiving request State; Nginx read to the client header information, that is, the number of connections;
Writing: The number of connections in the process of processing a request or sending a response when the request has been received; The number of header information returned to the client by Nginx. That is, the number of response data to the client;
Waiting: The number of connections that remain in connection mode and are active; When Keep-alive is turned on, this value is equal to active– (reading + writing), meaning that Nginx has finished processing and is waiting for the next request instruction to reside in the connection.
Rewrite regex replacement flags;

Role: Route rewriting is a very important basic function in a Web server. With route rewriting, URLs can be structured to be more semantic (useful for SEO). In addition, URLs that are shared may cause URLs to fail due to program routing changes, and routing overrides can be a good solution to such problems.
Regex: The regular expression used to match the URI. Use parentheses "()" to mark what you want to intercept.
Usage Environment: Server, location, if
Note: The directive redirects the URI based on an expression, or modifies the string. Directives are executed according to the order in the configuration file. Note that the rewrite expression is valid only for relative paths;


Rewrite ^/images/(. *\.jpg) $/imgs/$1 break; Http://

1) Last: Once this rewrite rule rewrite is complete, it is no longer processed by the other rewrite rules, but the user agent re-initiates the request again to the rewritten URL and executes a similar process from the beginning;
2) Break: Once this rewrite rule rewrite is complete, the new URL is re-initiated by the user agent and will no longer be checked by any rewrite rules in the current location;
3) Redirect: Returns the new URL with a 302 response code (temporary redirect).
4) Permanent: Return the new URL with 301 Response code (permanent redirect);

) if
Syntax: if (condition) {...}
Application environment: Server, Location
(1) Variable name:
The value of the variable is an empty string, or it starts with "0", or false; The others are true;
(2) A comparison expression consisting of a variable as an operand;
A similar comparison operator can be used to test the =,!=;
(3) Pattern matching operation for regular expressions:
~: Case-sensitive pattern matching check;
~*: Case-insensitive pattern matching checks;
!~ and!~*: Reverse the above two kinds of tests;
(4) Test path for file possibility:-F,!-f
(5) test the possibility of specifying a path as a directory:
(6) The existence of the test file:-E,!-E
(7) Check whether the file has Execute permission:-X,!-x
For example:

if ($http _user_agent ~* MSIE) {rewrite ^ (. *) $/msie/$1 break;}

15) picture anti-theft chain;

Syntax: Valid_referers None | Blocked | Server_names | String ...;
Default value:-
Configuration segment: Server, location
Function: Specify a valid source ' Referer ', which determines the value of the built-in variable $invalid_referer, if the Referer header is included in this legitimate URL, the variable is set to 0, otherwise set to 1. This variable is not case-sensitive.

Parameter description:

None: "Referer" source with empty head condition
Blocked: "Referer" source header is not empty, but the value inside is removed by proxy or firewall, these values do not start with http:/or https://.
Server_names: The "Referer" source header contains the current server_names (current domain name)
Arbitrary string: Any string that defines the server name or optional URI prefix. hostname can use * start or end, in the process of detecting the source header, the host port in the source domain name will be ignored
Regular expression: Regular expressions, ~ represents a string that excludes https://or http://.

Location ~* \. (jpg|gif|jpeg|png) $ {

Valid_referer none blocked; if ($invalid _referer) {rewrite ^/;}

16) custom access log format;

Log_format Main ' $remote _addr-$remote _user [$time _local] "$request" "$status $body _bytes_sent" $http _re                 Ferer "" "$http _user_agent" "$http _x_forwarded_for"; Access_log Logs/access.log Main;

Note: The variables are built in Nginx module.

Second, the network connection related configuration:

1. Keepalive_timeout time;
Long connection timeout, default is 75s;

2. Keepalive_requests N;
The maximum number of resources allowed to be requested on a long connection;

3. keepalive_disable [Msie6|safari|none];
The user agent of a bit-specified type disables long connections;

4. Tcp_nodelay On|off;
Whether to use the Tcp_nodelay option for long connections;

5. Client_header_timeout time;
Reads the timeout length of the header of the HTTP request message;

6. Client_body_timeout time;
Reads the timeout length of the body portion of the HTTP request message;

7. Send_timeout time;
The timeout of sending the response message is long;

---The first part to complete!

This article is from the "Yangbin" blog, make sure to keep this source

Nginx from getting started to mastering "(2nd (Total 3 sections)"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.