Nginx Quick start
Nginx profile
Nginx(pronounced engine X) is a lightweight, high-performance Web server, reverse proxy server, cache server, E-mail (IMAP/POP3) proxy server based on an asynchronous framework distributed under a BSD-like protocol. Developed by Russian programmer Igor Sysoev, it was originally used by Rambler.ru, a large Russian website, and Rambler, a search engine.
Nginx characteristics
Advantages:
Summary of most prominent advantages: 5W high concurrency, good at handling static files, simple configuration, stable.
- High concurrency: Developed based on epoll/ Kqueue model,Supports high concurrency“Officials say they support Gundam
5w
Response to the number of concurrent connections - Less memory consumption:
Good at handling static files
, consumes less memory and resources than other Web services, such as Apache - Simple and stable: Simple configuration (
A CONF file
), simple to run (Nginx command
), and the operation is stable - High degree of modularization: function module plug-in design, you can freely configure the corresponding functions.
- Support for Rwrite rewrite rules: Customized high-quality distribution can be achieved based on key request points such as domain names and urls.
- Low cost: Nginx’s load balancers are powerful and free and open source, and cost is relatively low compared to hundreds of thousands of hardware load balancers.
- Support for multiple systems: Nginx code written entirely in C language from scratch, can be compiled and used on various systems.
Disadvantages:
- Poor dynamic handling: Nginx is good at handling static files, but not as good at handling dynamic pages as heavyweight Web software like Apache.
- Rewrite is weak: Although Nginx has plenty of support for rewrite, it lacks the capabilities of heavyweight Web software such as Apache.
Nginx deployment
The installation
- The installation of the nginx
apt-get install -y build-essential libssl-dev libtool libpcre3 libpcre3-dev make openssl zlib1g-dev
apt-get install nginx -y
Copy the code
- Check the effect
netstat -tnulp | grep nginx
Copy the code
- Service related commands
systemctl start|stop|reload|... Nginx start, stop, reload nginx/etc/init. D/nginx start | stop | reload |... /usr/sbin/nginx ... nginx -VCopy the code
- Nginx service-related commands
Nginx -v nginx -v nginx -s stop nginx -s reload nginx -t check the default configuration file nginx -t -c file.conf Specifies the configuration file to checkCopy the code
- Remove related commands
- View nginx-related software
dpkg --get-selections|grep nginx
Copy the code
- Remove nginx, including associated files
apt-get --purge remove nginx
apt-get --purge remove nginx-common
apt-get --purge remove nginx-core
Copy the code
Nginx Configuration Overview
Nginx Software Directory:
- Working directory: /etc/nginx
- Execute file: /usr/sbin/nginx
- Log directory: /var/log/nginx
Startup file
: / etc/init. D/nginx- A web directory:
- /var/ WWW/HTML/index.nginx-debian.html
- The home file of /usr/share/nginx/html is index.html
Nginx configuration file:
The default file
: / etc/nginx/nginx. Conf- /etc/nginx/{sites-available/sites-enabled/conf.d}
- File structure:
- Global configuration segment
- The HTTP configuration section
- Server configuration section project or application
- Location Indicates the URL of the configuration segment
- Server configuration section project or application
Nginx access principle
The configuration,
(The most important part)
Global configuration segment
The configuration of global and service-level properties is as follows:
User (worker) worker_processes Increases the number of concurrent connections. Keep it consistent with the CPU. Eight-core Settings eight error_log Nginx error log PID PID events when the Nginx service is started Define event-related attributes worker_connections Maximum number of connections a process is allowed to process use Defines the kernel model usedCopy the code
The HTTP configuration section
Configure common configurations of the server
include mime.types; Default_type application/octet-stream; # default file type sendFile on; Enable efficient file transfer mode. autoindex on; # Enable directory list access, suitable for download server, default disabled. tcp_nopush on; Tcp_nodelay on; Keepalive_timeout 120; # long connection timeout, in seconds # Enable gzip compressed outputCopy the code
Common configuration attributes of the Server
Common styles Server {LISTEN port; Server_name Host name; . }Copy the code
The most important attributes of the Server configuration segment are LISTEN and server_name. Both are used to match and process requests.
Listen properties
-
Function: Defines the IP address and port monitored by the Server. The Server performs the next match only when the IP address and port match
-
Form of expression:
In the form of | describe | The sample | Complete sample |
---|---|---|---|
IP:Port | Address exact representation style | Listen 10.10.10.10:99 | Listen 10.10.10.10:99 |
IP | Automatic listening IP: address 80 | Listen 10.10.10.10 | Listen 10.10.10.10:80 |
Port | Automatic listening on the full address :Port | Listen or [: :] 99:99 | Listen 0.0.0.0:99 |
default_server | The default address is automatically used | listen default_server | listen localhost:80 |
- Principle of use:
- Server_name = Port = Port = Port = Port = Port = Port
A common understanding is that when we match more than one IP:Port, the following Server_name will take effect
)
- Server_name = Port = Port = Port = Port = Port = Port
Server_name properties
- Function: Defines the domain name that the Server listens to. Perform the next step only when the domain name matches
- Form of expression:
format | Complete style | Prefix regular style | Postfix regular style | Prohibit illegal domain names or IP addresses |
---|---|---|---|---|
In the form of | www.example.com | * .example.com | www.example. * | _ |
- Principle of use:
Full styles are preferred
And then usePrefix regular style
And finally usePostfix regular style
.If the pattern of the re is the same, the match is the longest, otherwise the rule is illegal.- Invalid domain name /IP address: an invalid IP address or domain name is requested from the host
The root attribute
- Defines the path of the HTML file requested by the Server
- Form of expression:
root /var/www/html;
Copy the code
The index attribute
- Purpose: Defines the file name or format to be returned in response to a request
- Form of expression:
index index.html index.htm index.nginx-debian.html;
Copy the code
The return attribute
- Purpose: Defines the HTTP status code returned in response to a request
- Form of expression:
return 444;
Copy the code
Location Common configuration properties
Location responds and processes requests based on the path and keywords matched by the Server.
Grammar:
location optional_modifier location_match { ... }
location @name { ... }
Copy the code
Optional_modifier is the matching condition, location_match is the matching style, and {} is the operation to be performed.
There are two main matching conditions: regular/prefix characters.
Match rule
- Regular match
type | meaning | The matching way | priority | style |
---|---|---|---|---|
~ |! ~ | Ordinary regular – sensitive | not sensitive | Regular symbol | 3 | location ~ .(jpe? g)$ {} |
~ * |! ~ * | Ordinary regular – not sensitive | sensitive | Regular symbol | 3 | location ~* .(jpe? g)$ {} |
- Ordinary match
type | meaning | The matching way | priority | style |
---|---|---|---|---|
= / path | An exact match | The prefix | 1 | location = /image {} |
^ ~ | Give priority to match | The prefix | 2 | location ^~ /page {} |
@ | Internal redirection | The prefix | location @name {} | |
Empty / | General matching | The prefix | 4 | location / {} |
Principle of use:
- Prerequisite: Obtain based on the request URL
uri
That is, the part other than the domain name /IP used for location matching - If there is an exact match, that is, the =/ path, the match ends when a match is found.
- Location = path {} or location full path {}
- If there is a priority match, that is, ^~, the match ends after the match is found.
- The location ^ ~ path
- If there is a regular match, namely ~ |! ~ * | | ~! ~*. After a match is found, the match will continue until a suitable one is found
- Location ~* regular character {}
- If multiple matches are made, the longest location_match is used.
Match the sample
Common examples:
- The access effect is as follows:
- Access the root directory /, for example
http://a.com/
Will match rule A - access
http://a.com/login
Will match rule B - access
http://a.com/static/a.html
Will match rule C - access
http://a.com/a.gif
.http://a.com/b.png
Rules D and E are both suitable, and rule D is preferentially used, whilehttp://a.com/static/c.png
Rule C is preferentially matched - access
http://a.com/a.PNG
Matches rule E, because rule E is case insensitive. - access
http://a.com/a.XHTML
Use rule F. - access
http://a.com/category/id/1111
Then rule H is finally matched.
- Access the root directory /, for example
@ name sample
@ is used to define a name location. It is mainly used for internal redirection and cannot be used to process normal requests. Its usage is as follows:
location / { try_files $uri $uri/ @custom } location @custom { # ... Do something # custom named location can't be nested in another location}Copy the code
Note the following about/at the end of the URL:
It does not affect whether the location_match character in location is "/"
. /user/ equivalent to /user.Access to the website domain (http://sswang.com/) is not affected by the end of the "/". Because the browser will automatically complete the "/"
.For access to the web site domain after the path (http://sswang.com/other/). The slash at the end is important
.
- A “/” at the end of the URL indicates a directory. No “/” indicates a file, and a redirection will occur if the file is not found.
- /other/ : Indicates that the server automatically searches for the default file in the directory.
- /other: indicates that the server searches for other files first. If it cannot find other files, the server takes Other as a directory and redirects it to /other/ to find default files in this directory.
Location Common actions:
There are many common functional attributes inside location, such as basic attributes, temporary jumps, access control, directory lists, and so on.
- Basic attributes
location / {
root /var/www/html; # specify the path of the file responding to the request
index index.php index.html index.htm; Specify the default file name to respond to the request
expires 7d; Specifies the expiration time of the file in response to the request, typically for static files
try_files $uri $uri/ =404; If there is a file in the path specified by root, return an error
}
Copy the code
- Temporary jump
location = /test/ {
return 302 http://sswang.com/; # when accessing the old URL, temporarily jump to the new url, both urls are not invalid
}
Copy the code
- Access control
location /nginx-status {
stub_status on; The nginx status page is disabled by default
allow 192.1688.14.; Allow access address
deny all; Disable all access by default} Note: This function relies on the ngx_http_stub_status_module module (not installed by default, requires custom installation)Copy the code
- Directory listing
location /upload {
alias /var/www/upload; # specify the path to view the file list (absolute path)
autoindex on; Enable automatic directory indexing
autoindex_exact_size off; # Default on, display the exact file size (bytes). Off Indicates the approximate file size (kB/MB/...).
autoindex_localtime on; By default, the file time is GMT. On: displays the server time of the file} Note: The alias does not allow files specified by the index attribute to appear in the directory specified by the index attribute.Copy the code
root VS alias
- Both root and alias serve the same purposeSpecifies the path to the file used in response to the requestThey are only slightly different
- Root indicates that location matches the content
Relative paths
- Alias stands for a
Absolute path and must end with "/"
- In general, you configure root in location/and alias in location /other
- Root indicates that location matches the content
Location /img/ {alias /var/ WWW /image/; }Copy the code
Location /img/ {root /var/ WWW /image; }Copy the code
- Nginx :/ var/ WWW /image/
- Nginx :/ var/ WWW /image/img/
Location Core Action
Nginx configuration syntax flexible, very high control system. The try_files directive, named location, was introduced after 0.7 to partially replace the rewrite configuration.
- Command syntax
try_files file ... uri
try_files file ... =code
Copy the code
Returns the contents of the file. Otherwise, internal redirection (URI) or status code (code) is performed.
- Common example
Returns the specified URI if it can be found, otherwise returns an error status code404
try_files $uri $uri/ =404; If the specified file can be found1/2.HTML then returns the corresponding content, otherwise returns6.HTML file content try_files1.html 2.html /6.html; Return the specified URI if it can be found, otherwise internally redirect to @backup location try_files $ur@backup;Copy the code
Note: If the last address is a URI, then the URI must exist, otherwise something is wrong