In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/02 Report--
Nginx is a high-performance HTTP and reverse proxy server, as well as an IMAP/POP3/SMTP proxy server. Nginx was developed by igor sysoev for the second most visited Rambler.ru site in Russia.
1. Installation and configuration of nginx
Download address: http://nginx.org/download/nginx-1.12.1.tar.gz
Installation preparation: nginx depends on the pcre library, so you need to install pcre pcre-devel first.
Yum install pcre pcre-devel-ymkdir / root/toolscd / root/toolswget http://nginx.org/download/nginx-1.12.1.tar.gztar zxf nginx-1.12.1.tar.gz cd nginx-1.12.1useradd-s / sbin/nologin nginx- M./configure\-- user=nginx\-- group=nginx\-- prefix=/usr/local/nginx\-- with-http_ssl_module\-with-http_stub_status_modulemake & & make installecho $? ln-s / usr / local/nginx/sbin/nginx / usr/local/sbin/nginxcd / usr/local/nginx
[root@localhost nginx] # tree
.├── conf # profile │ ├── fastcgi.conf │ ├── fastcgi.conf.default │ ├── fastcgi_params │ fastcgi_params.default │ ├── koi-utf │ ├── koi-win │ ├── mime.types │ ├── mime.types.default │ ├── nginx.conf nginx.conf.default scgi_params ├── scgi_params.default │ ├── uwsgi_params │ ├── uwsgi_params.default │ └── win-utf ├── html # Web File │ ├── 50x.html │ └── index.html ├── logs # Log File └── sbin # main binary ├── nginx
1) nginx signal control:
TERM,INT quick shutdown
QUIT gracefully shuts down the process, that is, wait for the request to finish before closing
HUP changes the configuration file and rereads the configuration file smoothly
USR1 reread logs, which are used when logs are separated by month and day
USR2 smooth upgrade
WINCH gracefully shuts down the process and works with USR2 to upgrade
Start nginx:
/ usr/local/nginx/sbin/nginx
Restart nginx:
Kill-QUIT `cat / usr/local/nginx/logs/ nginx.pid` & & / usr/local/nginx/sbin/nginx
Reload the configuration file:
Kill-HUP `cat / usr/local/nginx/logs/ nginx.pid`
/ usr/local/nginx/sbin/nginx-s reload
Stop nginx:
Kill-INT `cat / usr/local/nginx/logs/ nginx.pid`
/ usr/local/nginx/sbin/nginx-s stop/quit
Reread the log file:
Kill-USR1 `cat / usr/local/nginx/logs/ nginx.pid`
/ usr/local/nginx/sbin/nginx-s reopen
2) nginx configuration file:
Access_log log format variable description:
$remote_addr # remote client IP
$remote_user # client user information
$time_local # Local time
$request # request method, path and version
$status # response status
$body_bytes_sent # number of bytes sent to the client
$http_referer # where did the last page come from
$http_user_agent # client agent information
$http_x_forwarded_for # proxy server forwarding address
# user nobody; # run user worker_processes 1; # worker process, usually CPU number * core number # global error log # error_log logs/error.log; # error_log logs/error.log notice;#error_log logs/error.log info;#PID file # pid logs/nginx.pid;events {use epoll # epoll is a way of multiplexing IO (I/OMultiplexing), but only for kernels above linux2.6, it can greatly improve the performance of nginx. # generally, it is the feature of configuring nginx links, such as a worK can allow multiple links worker_connections 1024 at the same time; # refers to a maximum of 1024 links allowed by a process} http {# configure the main segment include mime.types of the http server. # set the mime type, which is defined by the mime.type file default_type application/octet-stream; # set the log format # log_format main'$remote_addr-$remote_user [$time_local] "$request" #'$status $body_bytes_sent "$http_referer" # "$http_user_agent"$http_x_forwarded_for"' The # access_log logs/access.log main; sendfile on; # instruction specifies whether nginx calls the sendfile function (zero copy mode) to output files. For ordinary applications, it must be set to on. If it is used for downloading and other application disk IO heavy-load applications, it can be set to off to balance the processing speed of disk and network Ibano and reduce the uptime of the system. # tcp_nopush on; # keepalive_timeout 0; keepalive_timeout 65; # connection timeout # gzip on; # enable gzip compression # set request buffer client_header_buffer_size 1k; large_client_header_buffers 4 4k # set the upstream mysvr {# weigth parameter of the load balancer server list to indicate the weight. The higher the weight, the greater the probability of being assigned # the Squid on this machine opens port 3128 server 192.168.8.1 weight=5; server 3128 weight=5; server 192.168.2 weight=5; server 80 weight=1; server 192.168.8.3 upstream mysvr 80 weight=6;} server {# virtual host listen 80 # listen on port 80 server_name localhost; # define access using www.xx.com # charset koi8-r; # set the access log of this virtual host # access_log logs/host.access.log main; # default request location / {root html; # define the default site root location index index.html index.htm of the server # define the name of the index file on the home page} # define the error prompt page # error_page 404 / 404.html; # redirect server error pages to the static page / 50x.html # error_page 500502 503504 / 50x.hml; location = / 50x.html {root html } # reverse proxy # location ~\ .php$ {# proxy_pass http://127.0.0.1; #} # forward the PHP dynamic page to the PHP program for processing # location ~\ .php$ {# root html; # fastcgi_pass 127.0.0.1 php$ 9000 # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME / scripts$fastcgi_script_name; # include fastcgi_params;}
3) practical application: shell+ timing task + nginx signal management, and the completion log is stored by date.
Analysis ideas:
At 00:00:01 in the morning, rename yesterday's log and put it in the appropriate directory.
Then the USR1 information number controls nginx to regenerate new log files.
Specific script:
#! / bin/bashbase_path='/usr/local/nginx/logs'log_path=$ (date-d yesterday + "% Y% m") day=$ (date-d yesterday + "% d") mkdir-p $base_path/$log_pathmv $base_path/access.log $base_path/$log_path/access_$day.log#echo $base_path/$log_path/access_$day.logkill-USR1 `cat / usr/local/nginx/logs/ nginx.pid`
Scheduled task
Crontab Editing scheduled tasks
01 00 * / xxx/path/b.sh 00:01 every day (recommended between 02 and 04:00, system load is small)
4) location syntax
Location has the meaning of positioning, and different positioning is carried out according to Uri.
In the configuration of virtual host, it is essential. Location can locate different parts of the website to different processing methods.
For example, when you encounter .php, how do you call the PHP interpreter?-- location is required
Syntax of location
Location [= | ~ | ~ * | ^ ~] patt {
}
Square brackets can not write any parameters, which is called general matching
You can also write parameters.
Therefore, large types can be divided into three types.
Location = patt {} [exact match]
Location patt {} [general match]
Location ~ patt {} [regular match]
How does it work?
First of all, let's see if there is an accurate match, and if so, stop the matching process.
Location = patt {config A} if $uri = = patt, the match is successful, use config A location = / {root / var/www/html/; index index.htm index.html;} location / {root / usr/local/nginx/html; index index.html index.htm;}
If you visit http://xxx.com/
The positioning process is
1: accurate matching "/" to get the index page as index.htm
2: visit / index.htm again. This internal transfer uri is already "/ index.htm".
The root directory is / usr/local/nginx/html
3: final result, visited / usr/local/nginx/html/index.htm
Regularities also come to participate.
Location / {root / usr/local/nginx/html; index index.html index.htm;} location ~ p_w_picpath {root / var/www/p_w_picpath; index index.html;}
If we visit https://cache.yisu.com/upload/information/20200309/32/37286.jpg
At this point, "/" matches "/ p_w_picpath/logo.png"
At the same time, "p_w_picpath" regular and "p_w_picpath/logo.png" can also match, who plays a role?
The results of regular expressions will be used.
The picture will really visit / var/www/p_w_picpath/logo.png
Location / {root / usr/local/nginx/html; index index.html index.htm;} location / foo {root / var/www/html; index index.html;}
We visit http://xxx.com/foo
For uri "/ foo", the patt of both location can match them.
That is,'/ 'can match from the left prefix' / foo','/ foo' can also match the left prefix'/ foo'
At this point, really visit / var/www/html/index.html
Reason: the'/ foo' match is longer, so use it.
5) rewrite rewriting
Instructions used in rewriting
If (condition) {} set the condition and then rewrite it
Set # set variable
Return # return status code
Break # Pop out of rewrite
Rewrite # rewrite
If syntax format
If space (condition) {
Rewrite mode
}
What about the terms and conditions?
Answer: there are three ways to write
1: "=" to judge equality, used for string comparison
2: "~" matches with regularities (the regularities here are case sensitive)
~ * case-insensitive regularity
3:-f-d-e to determine whether it is a file, a directory, or whether it exists.
Example:
If ($remote_addr = 192.168.1.100) {return 403;} if ($http_user_agent ~ MSIE) {rewrite ^. * $/ ie.htm; break; # (no break will loop redirect)} if (!-e $document_root$fastcgi_script_name) {rewrite ^. * $/ 404.html break }
Note: we also need to add break here. Take the non-existent page xx.com/dsafsd.html as an example. Let's observe the access log. The access path shown in the log is still GET / dsafsd.html HTTP/1.1.
Tip: the rewrite inside the server is not the same as the 302 jump. If you jump, the URL changes to re-http the request 404.html, while the internal rewrite, the context remains the same, that is, fastcgi_script_name is still dsafsd.html, so it will be redirected in a loop. set is used to set variables and can be used as a flag to achieve multi-conditional judgment. Achieve the effect of rewrite_condition under apache
As follows: judge IE and rewrite, and instead of break;, we use the set variable to achieve our goal
If ($http_user_agent ~ * msie) {set $isie 1;} if ($fastcgi_script_name = ie.html) {set $isie 0;} if ($isie 1) {rewrite ^. * $ie.html;}
Rewrite syntax
Position pattern after orientation of Rewrite regular expression
Goods-3.html-> Goods.php?goods_id=3goods- ([\ d] +)\ .html-> goods.php?goods_id = $1 location / ecshop {index index.php;rewrite goods- ([\ d] +)\ .html $/ ecshop/goods.php?id=$1;rewrite article- ([\ d] +)\ .html $/ ecshop/article.php?id=$1;rewrite category- (\ d +)-b (\ d +)\ .html / ecshop/category.php?id=$1&brand=$2 Note: when rewriting with url, if there is "{}" in the regular, the regular should be enclosed in double quotation marks.
6) gzip compression
Principle: the browser-request-> declares that it can accept gzip compression or deflate compression or compress or sdch compression
From the point of view of the http protocol-- the request header declares acceopt-encoding: gzip deflate sdch (refers to the compression algorithm, in which sdch is a compression method advocated by google, and there are not many servers supported at present) the server-> response-- compress the content in gzip mode-> send it to the browser to browse 80 bytes, and compression also consumes CPU resources. Smaller files do not need to be compressed
7) nginx cache settings improve website performance
For the pictures of the website, especially the news stations, once the pictures are released, the changes may be very small. We hope that after a user visit, the picture will be cached on the browser side of the user for a long time.
Yes, use the expires setting of nginx.
Set the expiration time in nginx, very simple, in the location or if section, to write.
Format: expires 30s
Expires 30m
Expires 2h
Expires 30d
(note: the date of the server should be accurate. If the date of the server lags behind the actual date, the cache may be invalidated.)
In addition, 304 is also a good caching method.
The principle is: the server responds to the content of the file, and responds to the etag tag at the same time (the signature of the content, when the content changes, it also changes), and last_modified_since two tag values
The next time the browser requests, the header information sends these two tags, and the server detects whether the file has changed. If not, the header information is returned to etag,last_modified_since directly.
The browser knows that the content has not changed, so it calls the local cache directly.
This process also requests the server, but the content is very little.
For those with a short change period, such as static html,js,css, it is more suitable to use this method.
8) nginx reverse proxy server + load balancer
It is very simple to use nginx for reverse proxy and load balancing.
Support two uses: 1 proxy and 1 upstream, which are used for reverse proxy and load balancing, respectively
Upstream load balancing mechanism:
Polling-requests to the application server are distributed on a circular basis: (the default configuration is polling)
Http {upstream myapp1 {server srv1.example.com; server srv2.example.com; server srv3.example.com;} server {listen 80; location / {proxy_pass http://myapp1;}
Minimum connections-the next request is assigned to the server with the least number of active connections:
Upstream myapp1 {least_conn; server srv1.example.com; server srv2.example.com; server srv3.example.com;}
The ip-hash-hash function is used to determine which server (based on the client's IP address) should be selected for the next request.
Upstream myapp1 {ip_hash; server srv1.example.com; server srv2.example.com; server srv3.example.com;}
Upstream parameter description:
The weight of the weight=1 # server, the larger the higher, the default is 1
Max_conns=1 # limits the maximum number of active links with the proxy server at the same time. Default is 0.
Max_fails=1 # makes the server unavailable within the number of failed connections with the server. When used with fail_timeout, the default is 1.
Fail_timeout=10 # if the number of connections is not successful, consider that the server is unavailable for a long time
Backup # Mark the server as a backup server
Down # marks the server as permanently unavailable
Taking the reverse proxy as an example, nginx does not process the related requests of php itself, but forwards the related requests of php to apache for processing.
If there are multiple servers in the reverse proxy backend, load balancing can be formed naturally.
But how does proxy_pass point to multiple servers?
Bind multiple servers together with a group name specified by upstream, and then proxy_pass points to the group:
Do reverse proxy and load balancing for image server:
# user nobody;worker_processes 1 the errorless 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 Upstream imagserver {# configure the load balancing server server 172.16.32.100 weight=1 max_fails=3 fail_timeout=10; server 172.16.32.100 weight=1 max_fails=3 fail_timeout=10; server 82 weight=1 max_fails=3 fail_timeout=10;} server {listen81;server_namelocalhost;location / {root html; index index.php index.html index.htm; access_log logs/81_access.log main;}} server {listen82;server_namelocalhost;location / {root html Index index.php index.html index.htm; access_log logs/82_access.log main;}} server {listen 80; server_name localhost; gzip on; gzip_buffers 32 4k; gzip_comp_level 6; gzip_types text/plain p_w_picpath/jpeg application/xml; gzip_vary on; # charset koi8-r; # access_log logs/host.access.log main Location / {root html; index index.php index.html index.htm;} location ~ *\. (jpg | jpeg | gif | png) {# configure a reverse proxy to forward the picture request to the server group proxy_set_header X-Forwarded-For $remote_addr; # and pass the client request IP to the proxy server log $http_x_forwarded_for proxy_pass http://imagserver; } # error_page 404 / 404.html; # redirect server error pages to the static page / 50x.html # error_page 500502503504 / 50x.html; location = / 50x.html {root html } # pass the PHP scripts to FastCGI server listening on 127.0.0.1 php$ 9000 # location ~\. Php$ {root html; proxy_set_header X-Forwarded-For $remote_addr; fastcgi_pass 127.0.0.1 php$ 9000; include fastcgi.conf;}}
-- end
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.