- http module
- server module (virtual host configuration)
-
Location Module
- basic grammar
-
Match Type
- Equals sign matching (=)
- Regular Match (~)
- Regular matches that ignore case (~*)
- Common commands
- Nested locations
- reverse proxy
-
load balancing
- Step 1: Define the Upstream Block
- Step 2: Configure the Server and Location blocks
- Sample Configuration
- Load Balancing Policy
-
Q&A
- What is the difference between root and alias?
Nginx configuration files are usually located in the
/etc/nginx/
or/usr/local/nginx/conf/
The exact location depends on your system and how it is installed. Configuration files are at the heart of Nginx and are used to define how the server operates and how requests are handled.
http module
user nginx;
worker_processes auto;
error_log /var/log/nginx/;
pid /run/;
events {
worker_connections 1024;
}
http {
include /etc/nginx/;
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 /var/log/nginx/ main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx//*.conf;
include /etc/nginx/;
}
Explanation of the various components
-
user: Defines the users and groups that run the Nginx process.
-
worker_processes: Specifies the number of worker processes that Nginx should start.
-
error_log: Defines the location of the error log.
-
pid: Defines the location of the Nginx process ID file.
-
events: Configure the event handling model, e.g. worker_connections sets the maximum number of connections that each worker process can have open at the same time.
-
http: This is the main part of Nginx configuration, including global settings, virtual host configuration, and so on.
-
include
: Used to include other configuration files. -
log_format
cap (a poem)access_log
: Used to define the format and location of the access log. -
sendfile
,tcp_nopush
,tcp_nodelay
,keepalive_timeout
: These are options for improving performance and optimizing network transmission. -
types_hash_max_size
: Size limit for caching MIME types. -
include
: The last twoinclude
statement is used to include additional configuration files, such as site configuration or module configuration.
server module (virtual host configuration)
existhttp
block, you can define multipleserver
blocks to configure different virtual hosts. Eachserver
The block can have the following parameters:
server {
listen 80; server_name ;
server_name ;
root /var/www/example ;
index ;
# Instead of "root", specify "/" to allow more flexibility in configuring other options.
location / {
try_files $uri $uri/ =404; }
}
# More location blocks for more detailed URL path matching and processing.
}
- listen: Defines the port and address on which the server listens.
- server_name: Defines the domain name or IP address. A secondary domain name can be configured.
- root: Define the web root directory.
- index: Define the default index file, if the default file in the root directory is not called and called, then index needs to be configured as.
- location: Defines the path matching rules and processing of URLs.
Location Module
in the server module.location
block is used to define how to handle HTTP requests that match a specific URL pattern.location
block allows you to specify different processing logic for different URL paths, such as static file serving, dynamic content processing, redirection, reverse proxying, load balancing, and so on. The following is a detailed explanationlocation
The different usage and syntax of the
basic grammar
location
The basic syntax of a block is as follows:
location [=|~|~*|^~] /pattern {
# Processing logic
}
included among these/pattern
is the pattern of the URL path, which can be an exact string, regular expression, or other match type.
Match Type
Suppose I have three files, in the /data/icons/ directory,
The equal sign matches (=
)
When prefixed with the equals sign, thelocation
will only match URL paths that are exactly equal. This is the most efficient type of match because Nginx can do direct lookups without regular expression matching.
location = / {
root /data/icons;
}
Regular Match (~
)
When using wavy lines as a prefix, thelocation
A regular expression will be used to match the URL path.
location ~ /favicon[2-3].ico {
root /data/icons;
}
Regular matches that ignore case (~*
)
Similar to regular matching, but ignores case. We will change it to.
location ~* /favicon[2-3].ico {
root /data/icons;
}
At this point, as we understand it, accessing / should display it properly, but it doesn't! You need to visit / to display it properly.
Why?
Because, just url and nginx this line configuration ignore case, let url go this line configuration rules, not url and actual access to resources ignore case. The actual access to the resource name case is still the same.
Common commands
existlocation
Within the block, you can define a series of directives to handle requests that are matched to. Common directives include:
-
root
: Setting thelocation
under the document root directory. -
alias
:: In conjunction with theroot
Similar, butalias
Maps URLs directly to file system paths. -
try_files
: Attempts to find the files in the given order. If it is not found, a default handler can be specified, such as forwarding to a back-end application. -
proxy_pass
: Used to set up a reverse proxy to access theserviceAnd non-static resources use this. -
rewrite
: Used to rewrite URLs or redirect requests. -
return
: Immediately returns an HTTP response code and optional content.
nestedlocation
location
Blocks can be nested within anotherlocation
within the block, allowing finer control. Example:
location / {
root /www/;
location ~ \.php$ {
root /var/www/;
fastcgi_pass 127.0.0.1:9000;
}
}
In this example, all requests are by default directed to the/www/
root directory, but.php
Requests with extensions are handled specially, pointing to the/var/www/
and sent to the PHP processor via FastCGI.
reverse proxy
Let's say you have a back-end application server running locally on port 8000, and you want to pass through Nginx all the calls to the requests are proxied to this backend server, you can use the following configuration:
server {
listen 80;
server_name ;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# Optional additional configurations
proxy_redirect off;
proxy_buffering off;
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
send_timeout 60s;
}
}
Interpretation Configuration
-
listen 80;
: Listens for requests on port 80. -
server_name ;
: Specify the server name to ensure that only theThe request is processed.
-
location / { ... }
: Defines that all requests should be proxied. -
proxy_pass http://127.0.0.1:8000;
: Forwards the request to local port 8000. -
proxy_set_header
: Set the header information passed by the proxy. This is important because the back-end server may need to know information about the original client. - (sth. or sb) else
proxy_
Configuration: These settings are used to optimize the performance and reliability of the proxy connection.
load balancing
Configuring load balancing in Nginx allows you to distribute client requests among multiple back-end servers to improve application availability and responsiveness, as well as increase system redundancy. The following are steps and sample configurations for configuring simple load balancing based on a polling (round-robin) policy using Nginx:
Step 1: Define the Upstream Block
First, you need to define aupstream
block, which will contain a list of a set of backend servers. Thisupstream
Blocks can be used by more than onelocation
Block references for load balancing.
Step 2: Configure the Server and Location blocks
Next, in theserver
block using thelocation
block to specify which requests should be proxied to the definedupstream
This way, Nginx will distribute requests to different backend servers according to the load balancing policy. In this way, Nginx will distribute requests to different back-end servers according to a load balancing policy.
Sample Configuration
Let's say you have two back-end application servers running on the:8000
cap (a poem):8000
, you can use the following configuration for load balancing:
upstream backend {
server :8000;
server :8000;
}
server {
listen 80;
server_name ;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
Interpretation Configuration
-
upstream backend { ... }
: defines a file namedbackend
of the upstream server group, which contains two back-end servers. -
server :8000;
respond in singingserver :8000;
: Specifies the address and port of the back-end server. -
proxy_pass http://backend;
: Tells Nginx to proxy the request tobackend
Upstream server group.
Load Balancing Policy
Nginx uses the round-robin policy by default, but you can use other policies such as least connections or hash. For example, to use the least connections policy, you can modify theupstream
The blocks are as follows:
upstream backend {
least_conn;
server :8000;
server :8000;
}
In this configuration, theleast_conn;
directive tells Nginx to choose the server with the lowest number of connections to handle new requests. There are other policy configurations that you can configure on your own, so I won't go into them here.
The above is my common configuration in the actual use of nginx, the remaining configurations in the actual use of the configuration after the continuation of the supplement ~ ~
Q&A
What is the difference between root and alias?
In Nginx'slocation
block using theroot
respond in singingalias
directive, the main difference between them is how the URL is resolved to the actual file system path. Although both directives are used to specify the root directory of a file, they work differently.
**root**
directives
root
directive is used to set a base directory when compared to thelocation
When used in combination, Nginx appends the requested URI (Uniform Resource Identifier) to theroot
directory is followed by the corresponding file or directory. This means that if theroot
set to/data/icons
and the URL request is/img/
then Nginx will try to set the/data/icons/img/
Find a file.
Example:
location / {
root /data/icons;
# Requesting /img/ will look for /data/icons/img/.
}
**alias**
directives
alias
directive is used to do a direct mapping of URLs to filesystem paths. When using thealias
whenThe path portion of the URL will be completely replaced with **alias**
Specified path, rather than attaching to it. This means that if thealias
set to/data/icons/img/
and the URL request is/img/
Then Nginx will be able to use it in the/data/icons/img/
Finds the file directly without putting the/img/
add inalias
behind the specified path.
Example:
location /img/ {
alias /data/icons/img/;
# A request for /img/ will look for /data/icons/img/.
}
Selection of useroot
neverthelessalias
It depends largely on your specific needs.
In general, good habits for nginx configuration are:
- Configure the root directory in location /
- Configure the alias directory in location /path