Getting Started with Nginx configuration

Source: Internet
Author: User
Tags nginx server

Thank you, the author of the Spirit of sharing, the original address: http://www.nginx.cn/591.html

Getting Started with Nginx configuration

The previous Nginx configuration is to explain the specific meaning of nginx configuration file, but for Nginx novice may confused.

See a good document today, translation to share to everyone, you can let the novice more detailed understanding of nginx configuration, can be said to be a prerequisite for nginx configuration.

Nginx is a lightweight, high-performance Web server designed to respond quickly to large volumes of static file requests and efficiently utilize system resources. Unlike Apache handling requests in a process-or thread-oriented manner, Nginx uses asynchronous event-driven models to perform more prominently under load.

Although Nginx can effectively serve static files, some people think that nginx processing dynamic content is not ideal. Unlike Apache servers, Nginx doesn't use the inline interpreter to handle dynamic content. Instead, dynamic content is dropped to cgi,fastcgi or Web servers such as Apache, and the results are returned to Nginx,nginx in return to the browser. This approach leads to a more complex deployment. For these reasons, using and configuring Nginx may be obscure. Nginx configuration feels more complex or not straightforward.

The premise of this article is that you use Nginx installation to install Nginx, if you use other methods or the system comes with the package installation, then the location of your configuration file and the following configuration file location may be different.

Nginx is the power of the configuration file to achieve, Nginx is a binary file Nginx read into a configuration file nginx.conf (nginx.conf may include a number of sub-profiles) to achieve a variety of functions.

Manage Profiles

Nginx uses nested curly brace syntax to define options. After installation, the main configuration file of Nginx is placed in/usr/local/nginx/nginx.conf. At the same time a default backup configuration file exists/usr/local/nginx/nginx.conf.default. The other child profiles also have a. Default end-of-backup profile: The default function is that when you modify a configuration file, you can quickly go back to the last useful state. We recommend that you always make a backup of the configuration file of the configured function, and you can end it with a date file. For example, you can use the following command to complete the date you have backed up.

------------------------------------------------------------------------------------
cp/usr/local/nginx/nginx.conf/usr/local/nginx/nginx.conf-20121224
------------------------------------------------------------------------------------

Reload the configuration file every time you finish modifying nginx.conf

------------------------------------------------------------------------------------
/usr/loca/nginx/nginx-t
Kill-hup ' Cat/usr/local/nginx/nginx.pid '
------------------------------------------------------------------------------------
Global Configuration

We split up a little bit. Introducing the default configuration file

------------------------------------------------------------------------------------
#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;}

------------------------------------------------------------------------------------

These are the default lines at the beginning of the configuration file. In a typical environment, you don't need to modify these options. There are several aspects of this section that need our attention:

    • All lines opened with the # number are comments and Nginx will not parse. The default configuration file has a number of comment blocks explaining the explanation
    • An instruction is preceded by a variable name (for example, worker_processes or PID) and then contains a parameter (for example, 1 or logs/nginx.pid) or multiple parameters (for example, "Logs/error.log notice")
    • All directives end with a semicolon
    • Some directives, like the one above, events can contain multiple sub-directives as parameters. These sub-directives are surrounded by curly braces.
    • Although Nginx does not parse whitespace characters (such as tab, space, and line breaks), good indentation can improve the efficiency of maintaining long-running profiles. Good indentation makes the profile read smoother and makes it easy to understand the configured strategy even a few months ago.

Let's continue reading the configuration file

------------------------------------------------------------------------------------
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; 
------------------------------------------------------------------------------------

The beginning of the "http {}" block is the same as the beginning of the configuration file and no modification is required for the standard configuration. Here we need to focus on these elements:

    • The starting "include" statement for this section contains the location of the/usr/loca/nginx/mime.types file to the nginx.conf file include statement. Include is useful for readability and organization of ningx.conf files.
    • You cannot use include too much, and if too many of the recursive include files are confusing, you need to use include wisely to ensure that the profiles are clear and manageable.
    • You can remove the comment before the log_format instruction and modify these lines to set the variable to the information you want to record.
    • The gzip instruction tells Nginx to use gzip compression to reduce bandwidth usage and speed up transmission. If you want to use gzip compression, you need to add the following configuration to the gzip location of the configuration file.
    • ------------------------------------------------------------------------------------
gzip on;        Gzip_http_version 1.1;        Gzip_comp_level 2; Gzip_types text/plain text/html text/css Application/x-javascript text/xml AP Plication/xml Application/xml+rss Text/javascript;
------------------------------------------------------------------------------------

There is no cost to using GIZP compression. It also increases CPU usage while reducing bandwidth. The parameters of the Gzip_cop_level range 1-9, 9 for the most CPU and 1 for the minimum CPU, and the default value is 1.

Also, note that the above fragment "HTTP {" is the first half of HTTP, and the rest of the solution continues below until the matching "}".

Virtual Machine Server Configuration

Our home is nginx.conf. The next configuration file is this

------------------------------------------------------------------------------------
        server {                 listen       80;                 server_name   localhost;                 access_log  logs/localhost.access.log  main;                 location / {                     root    html;                     index  index.html index.htm;                 }        }} 
------------------------------------------------------------------------------------

We can see that the http{} block ends here.

The server instruction block, like the one in the example above, is where our Nginx users primarily configure their own virtual hosting. There are many important instructions in the server block. The listen instruction tells Nginx to listen for connections on a specific hostname,ip or TCP port. By default, the HTTP service runs on port 80. These listen instructions are valid:

------------------------------------------------------------------------------------
Listen 127.0.0.1:80;listen Localhost:80;listen 127.0.0.1:8080;listen localhost:8080;listen 192.168.3.1 05:80;listen 192.168.3.105:8080;listen 80;listen *:80;listen 8080;listen *:8080;listen 12.34.56.77 : 80;listen 12.34.56.78:80;listen 12.34.56.79:80;
------------------------------------------------------------------------------------

In these examples, we can see a number of different ways of expression:

    • The first set of 2 instructions indicates that the server listens on port 80 on 127.0.0.1 or localhost, and localhost is typically defined in/etc/hosts pointing to 127.0.0.1
    • The second group is the same as the first group except that the port number is monitored at 8080 instead of 80.
    • The third set of examples defines the server listening on ports 80 and 8080 in 192.168.3.105
    • The fourth set of examples is to listen for specific ports on all addresses. Listen 80 is the same as listen *:80, listen 8080 is the same as listen *:80.
    • The last set of examples sets the server to listen only for requests on port 80 of 12.34.56.77/78/79.

Server_Name instructions can be set up based on the domain name of the virtual host, according to the content of the request header, an IP server can configure multiple domain names. The following parameters of the server_name are valid:

------------------------------------------------------------------------------------
server_name nginx.cn;server_name nginx.cn www.nginx.cn;server_name *.nginx.cn;server_name. nginx.cn;server_name Nginx.*;server_name nginx.cng bucknell.net brackley.org;server_name localhost Litchfield bleddington;server_name "";
------------------------------------------------------------------------------------

Multiple domain names are separated by a space. Nginx allows a virtual host to have one or more names, or you can use the wildcard character "*" to set the name of the virtual host. In the example above we see a lot of special places:

    • The first set of examples, first defined server_name as nginx.cn, then the request from http://nginx.cn will be sent to the host. The second example configures nginx.cn and www.nginx.cn, so requests from http://nginx.cn and http://www.nginx.cn are sent to this host.
    • *.nginx.cn and. nginx.cn are equivalent configurations, setting the host to handle all subdomains from nginx.cn, such as www.nginx.cn,blog.nginx.cn, etc.
    • The second set of server_name configures the nginx.*, which configures the server to handle all requests that begin with Nginx. For example, nginx.com,nginx.cn,nginx.net,nginx.baidu.com
    • The next set of first server_name configuration, sets the host to process requests from three domain names. Nginx allows setting a name that is not a valid domain name. For example, in the next configuration we can see three examples that are not valid domain names, localhost,litchfiled and Bledington. Nginx only looks for the domain name in the HTTP header of the request, but does not determine whether the domain name is valid, in this case the host names can be configured in the/etc/hosts. It is sometimes more appropriate to use a non-domain host name when you are debugging natively.
    • In the last set of examples, server_name is set to empty double quotes, which tells Nginx to catch all requests without hostname, or hostname is not specified in other server_name.

We continue to analyze the next server instruction block to see the access_log directive.

------------------------------------------------------------------------------------
Access_log logs/nginx.access.log;access_log/srv/http/ducklington.org/logs/access.log;access_log/var/log/nginx/ Access/ducklington.org;access_log off;
------------------------------------------------------------------------------------

In the first example, the log uses a relative path and the log file is placed in a directory sibling to the configuration file, where the log is stored in the/usr/local/nginx/logs/ Nginx.access.log; The next two examples define the complete absolute path; The last example is to close access log and not record access logs to the file.

The last part of the server block is the location instruction block, which is used to configure different responses to the server for different client request destinations.

Just like the server_name directive configures the Nginx processing request to use the information contained in the request, the location directive configures how the request responds to different locations resources. For example:

------------------------------------------------------------------------------------
Location/{}location/images/{}location/blog/{}location/planet/{}location/planet/blog/{}location ~ IndexPage. php$ {}location ~ ^/blogplanet (/|/index.php) $ {}location ~*. (PL|CGI|PERL|PRL) $ {}location ~*. (MD|MDWN|TXT|MKDN) $ {}location ^~/images/indexpage/{}location ^~/blog/blogplanet/{}location =/{}
------------------------------------------------------------------------------------

The first five examples are literal verbatim matches that match the part of the request URL that begins behind the domain name. Assuming a request http://www.nginx.cn, we assume that server_name has matched www.nginx.cn, then the "location/" command will capture the request. Nginx uses the location with the highest degree of matching. For example, http://ducklington.org/planet/blog/and http://ducklington.org/planet/blog/about/will match "Location/planet/blog", not " location/planet/"

Location configuration

For a particular request, once nginx matches a location to process. The response of the request is then determined by the instructions in the location block. Let's take a look at one of the most basic Locaiton configuration blocks.

------------------------------------------------------------------------------------
Location/{root HTML; Index index.html index.htm;}
------------------------------------------------------------------------------------

In this example the Chinese file root (doucument root) is located in the html/directory. According to Nginx installation directory/usr/local/nginx, the full path of this location is/usr/local/nginx/html. If a request access is located in the/blog/includes/styles.css file and no other location block matches, Nginx will use the file system's/usr/local/nginx/html/blog/includes/ Styles.css Response. Of course you can also set the root command with an absolute path.

The index directive tells Nginx which resource to use if the request does not have a file name. Therefore, if the request http://.ducklington.org/will be complete the resource location is/usr/local/nginx/html/index.html. If index is configured with multiple files, Nginx is processed sequentially until it finds the first existing complete resource. If index.html is not in the relevant directory, then index.htm will be used. If none of the two are present, a 404 error is returned.

Let's look at another example of the location directive, which is in the ducklington.org server instruction block.

------------------------------------------------------------------------------------
Root/srv/www/ducklington.org/public_html;location/{index index.html index.htm;}    Location ~. php$ {gzip off;    Include Fastcgi_params;    Fastcgi_pass 127.0.0.1:9000;    Fastcgi_index index.php; Fastcgi_param script_filename $document _root$fastcgi_script_name;}
------------------------------------------------------------------------------------

In this example, all requests ending in. php are processed by the second location block. The second statement block specifies a fastcgi handle for all requests. Other requests, Nginx will use the first location block to handle.

The request http://ducklington.org/will return/srv/www/ducklington.org/public_html/index.html if present, if it does not exist this returns/srv/www/ ducklington.org/public_html/index.htm, a 404 error is returned if none of the two are present.

The request http://ducklington.org/blog/will return the /srv/www/ducklington.org/public_html/blog/index.html if it exists and returns if it does not exist. /srv/www/ducklington.org/public_html/blog/index.htm, a 404 error is returned if none of the two are present.

Request http://ducklington.org/tasks.php will be sent to FastCGI to execute files located in/srv/www/ducklington.org/public_html/tasks.php.

the request http://ducklington.org/squire/roster.php will also use the fastcgi handle to execute at the/srv/www/ducklington.org/public_html/squire/ roster.pl file and returns the result.

Specific location matching rules This is not to say, do not understand can see here Nginx location match

Best practices

The above examples and explanations should be enough to allow you to configure your own Nginx server. Configuring Nginx Server Best practices is listed below.

First, put all the instructions for a specific server instruction block that you want to configure in a file, and then use the include statement to include it in the configuration file.

For example, to bind the ducklington.org domain name, first place the ducklington.org server instruction block configuration in/srv/www/ducklington.org/nginx.conf. Then add the instruction include/srv/www/ducklington.org/nginx.conf to the HTTP block in the configuration file. Like this:

------------------------------------------------------------------------------------
HTTP {# [...]      include/srv/www/ducklington.org/nginx.conf; # [...]}
------------------------------------------------------------------------------------

Original address: http://www.nginx.cn/591.html

Getting Started with Nginx configuration

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.