[Nginx Notes] nginx configuration file details, nginx configuration file details

Source: Internet
Author: User

[Nginx Notes] nginx configuration file details, nginx configuration file details

This article focuses on nginx configuration. For other basic concepts about nginx, we recommend that you refer to the official website description. Here we recommend the Nginx Beginner's Guide document, which is helpful for beginners to quickly understand nginx.

Obviously, the premise to take advantage of nginx's powerful advantages is to familiarize yourself with its configuration files and make proper configuration. The most important thing to learn about nginx configuration is to establish the following concepts:

The most important is that nginx is a reverse proxy first and HTTP server second, its first concern is not files but rather URLs, this changes the way we have to configure nginx.

That is to say, nginx is powerful in its high-performance reverse proxy function (it receives requests and passes them to the downstream servers that actually process requests; waits for downstream responses and returns them to the request initiator). Second, it can also provide static file access functions like normal webserver.

Take the default configuration file (conf/nginx. conf. default) after nginx source code compilation and installation as an example to describe important configuration items.
#user  nobody;worker_processes  1;#error_log  logs/error.log;#error_log  logs/error.log  notice;#error_log  logs/error.log  info;#pid        logs/nginx.pid;events {    worker_connections  1024;}http {    include       mime.types;    default_type  application/octet-stream;    #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  logs/access.log  main;    sendfile        on;    #tcp_nopush     on;    #keepalive_timeout  0;    keepalive_timeout  65;    #gzip  on;    server {        listen       80;        server_name  localhost;        #charset koi8-r;        #access_log  logs/host.access.log  main;        location / {            root   html;            index  index.html index.htm;        }        #error_page  404              /404.html;        # redirect server error pages to the static page /50x.html        #        error_page   500 502 503 504  /50x.html;        location = /50x.html {            root   html;        }        # proxy the PHP scripts to Apache listening on 127.0.0.1:80        #        #location ~ \.php$ {        #    proxy_pass   http://127.0.0.1;        #}        # 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;        #}        # deny access to .htaccess files, if Apache's document root        # concurs with nginx's one        #        #location ~ /\.ht {        #    deny  all;        #}    }    # another virtual host using mix of IP-, name-, and port-based configuration    #    #server {    #    listen       8000;    #    listen       somename:8080;    #    server_name  somename  alias  another.alias;    #    location / {    #        root   html;    #        index  index.html index.htm;    #    }    #}    # HTTPS server    #    #server {    #    listen       443 ssl;    #    server_name  localhost;    #    ssl_certificate      cert.pem;    #    ssl_certificate_key  cert.key;    #    ssl_session_cache    shared:SSL:1m;    #    ssl_session_timeout  5m;    #    ssl_ciphers  HIGH:!aNULL:!MD5;    #    ssl_prefer_server_ciphers  on;    #    location / {    #        root   html;    #        index  index.html index.htm;    #    }    #}}

1. hierarchical relationship of Nginx configuration file blocks

To familiarize yourself with the nginx configuration file, you must first understand the block division and the hierarchical relationship between blocks, understanding the nginx configuration inheritance model provides detailed and instance-based descriptions on THE hierarchy, hierarchy, or CONFIGURATION item type, INHERITANCE of CONFIGURATION items, and nested block definitions of each block, I will not go into details here.
We need to keep in mind the hierarchical relationship between the three blocks: http-> server-> location, which are the key blocks in the nginx configuration process.

2. Server block (Virtual Host)
Server block is mainly used to create virtual server. The most important setting items are:
1) listen
Set the listening address, port number, and UNIX-domain socket path. You can only set the listening address (ip address or hostname). In this case, port 80 is listened on by default, or you can only specify the listening port number. In addition, you can also set whether the server is the default server, whether the connection is ssl encrypted, proxy_protocol, and so on.
For detailed settings syntax and settings, refer to the official documentation here.
2) server_name
Set the Domain Name of the server block and support the exact domain name, domain name with wildcard characters, and regular expression formats. For specific rules, see here. After nginx receives the request URL, it searches for the server that processes the request based on the server_name configured by each server block. 1st matches are successful (the domain name specified by the request URL header matches server_name) server block is responsible for processing URL requests. According to the documentation,The specific search order priority is as follows (from high to low ):
A. the exact name
B. the longest wildcard name starting with an asterisk, e.g. "* .example.com"
C. the longest wildcard name ending with an asterisk, e.g. "mail .*"
D. the first matching regular expression (in order of appearance in the configuration file)
In fact, when configuring server_name, exact domain names, wildcard domain names starting with *, and wildcard domain names ending with * are stored in the three hash tables associated with listen port respectively. When nginx searches for server Blocks Based on server_name, it searches for the three hash tables in sequence in the above order. If one hash table hits a certain configuration, the search is complete, the user request URL is sent to the server block of the successfully matched server_name. If all three hash tables fail to be searched, server_name in the regular expression format is searched in sequence. Because reg exp match is the slowest, its search priority is the lowest.
Therefore,In actual use, we should configure the exact domain name as much as possible.
In addition, if you need to configure many server names or a server domain name that is very long, you should optimize the server_names_hash_max_size and server_names_hash_bucket_size configuration items respectively. For details, see the Optimization section of this document.
3) location
For more information, see the description in the next section.

3. Location Block
The following important rules need to be clarified about location block:
1)Except for the named location (named location) block, all other location blocks work on URLs without the query parameter, and only one location block works at a time. This is also the reason that directory configuration is usually placed in the top-level block, because the root directory setting defined in location/cannot be used for location/images, and if the root directory is set in the server block, this setting can be used for all location blocks (of course, you can rewrite the root directory settings for this block in the location block), whether to eliminate duplicate code or follow-up maintenance, it is much more convenient.
2)Nginx allocates the request URL Based on server_name in the location block.Nginx's match rules for URL and location blocks are as follows (the official website documentation is here):
A. First, find the location block defined by the prefix string. The block with the longest prefix will be recorded by nginx in all the location blocks with successful prefix string matching;
B. nginx then checks the location block defined by the regular expression in the order defined in the configuration file. When the regular expression matches a block successfully, the search is complete and the block is responsible for processing the URL, the entire match process ends;
C. If the location block specified by the regular expression does not match successfully, the block with the longest prefix match recorded in step 1 is returned, and the entire match process ends.
Notes:
A. The location block defined by the regular expression has a lower Search priority but a higher matching priority. This is different from the nginx server_name Search rules (server_name matches the Search priority and ends the search immediately after the match is successful.
B. location can also be precisely configured with equal signs (=). It has the highest matching priority. As long as the location matches the exact match, nginx immediately ends searching for the location block.
3)For detailed syntax rules, see the official website documentation.

4. Reverse Proxy Settings
When you are familiar with the basic configuration rules of the main blocks (http/server/location), configuring nginx to implement the reverse proxy server is actually very simple. In the location block, you can configure proxy_pass or fastcgi_pass.
In addition, you can also configure which source address request proxy to which downstream service (proxy_bind), whether to buffer downstream response headers, And the buffer size (proxy_buffering/proxy_buffer_size ), whether to cache the response results (proxy_cache.
For detailed configuration syntax, see Module ngx_http_proxy_module and Module ngx_http_fastcgi_module.

[References]

1. UNDERSTANDING THE NGINX CONFIGURATION INHERITANCE MODEL
2. NGINX CONFIGURATION PRIMER
3. Nginx Beginner's Guide

=========================================Eof ===

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: info-contact@alibabacloud.com 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.