CentOS7 installation and maintenance of nginx from entry to master

Nginx is a performance-oriented HTTP server that can reverse proxy HTTP, HTTPS and mail-related (SMTP, POP3, IMAP) protocol links. And provides [Load Balancing] (https://cloud.tencent.com/product/clb?from=10680) and HTTP caching. Its design makes full use of the asynchronous event model, reduces the overhead of context scheduling, and improves the server's concurrency capabilities. Modular design is adopted, and third-party modules with abundant modules are provided.

So about Nginx, there are these tags: "asynchronous" "event" "modular" "high performance" "high concurrency" "reverse proxy" "load balancing"

Linux system: Centos 7 x64 Nginx version: 1.11.5

installation##

Installation dependencies###

prce (redirection support) and openssl (https support, if you don't need https, you don't need to install it.)

yum install -y pcre-devel 
yum -y install gcc make gcc-c++ wget
yum -y install openssl openssl-devel 

CentOS 6.5 I chose the "basic server" when I installed it. By default, neither of these two packages have been installed, so both of them can be installed.

download###

All versions of nginx are here

wget http://nginx.org/download/nginx-1.13.3.tar.gz
wget http://nginx.org/download/nginx-1.13.7.tar.gz
# If wget is not installed#Download the compiled version
$ yum install wget
# Unzip the compressed package
tar zxf nginx-1.13.3.tar.gz

Compile and install###

Then enter the directory to compile and install, configure parameter description

cd nginx-1.11.5./configure

....
Configuration summary
 + using system PCRE library
 + OpenSSL library is not used
 + using system zlib library

 nginx path prefix:"/usr/local/nginx"
 nginx binary file:"/usr/local/nginx/sbin/nginx"
 nginx modules path:"/usr/local/nginx/modules"
 nginx configuration prefix:"/usr/local/nginx/conf"
 nginx configuration file:"/usr/local/nginx/conf/nginx.conf"
 nginx pid file:"/usr/local/nginx/logs/nginx.pid"
 nginx error log file:"/usr/local/nginx/logs/error.log"
 nginx http access log file:"/usr/local/nginx/logs/access.log"
 nginx http client request body temporary files:"client_body_temp"
 nginx http proxy temporary files:"proxy_temp"
 nginx http fastcgi temporary files:"fastcgi_temp"
 nginx http uwsgi temporary files:"uwsgi_temp"
 nginx http scgi temporary files:"scgi_temp"

If an installation error is reported, for example: "C compiler cc is not found", this is the lack of a compilation environment, just install it yum -y install gcc make gcc-c++ openssl-devel

If there is no error message, you can perform the following installation:

make
make install

nginx test###

There are two results when you run the following command. Generally, nginx will be installed in the /usr/local/nginx directory

cd /usr/local/nginx/sbin/./nginx -t
# nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
# nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

Set global nginx commands###

vi ~/.bash_profile

Add the following content to the ~/.bash_profile file

PATH=$PATH:$HOME/bin:/usr/local/nginx/sbin/export PATH

Run the command source ~/.bash_profile to make the configuration effective immediately. You can run the nginx command globally.

Boot from start##

Self-start method 1:

Edit the vi /lib/systemd/system/nginx.service file, without creating a touch nginx.service, then modify the following content according to the specific situation and add it to the nginx.service file:

[ Unit]
Description=nginx
After=network.target remote-fs.target nss-lookup.target

[ Service]

Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPIDExecStop=/bin/kill -s QUIT $MAINPIDPrivateTmp=true[Install]
WantedBy=multi-user.target

Description: describe the service
After: Describe the service category
[ Service] Service operating parameter settings
Type=forking is the form of background operation
ExecStart is the specific running command of the service
ExecReload is a restart command
ExecStop is a stop command
PrivateTmp=True means to allocate independent temporary space to the service
Note: [Service] start, restart, and stop commands all require absolute paths
[ Install] The related settings of service installation under run level can be set to multi-user, that is, the system run level is 3

Save and exit.

Set startup to make the configuration take effect:

systemctl enable nginx.service
# The following output indicates success

Created symlink from/etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.

Boot method two:

vi /etc/rc.local
# In rc.In the local file, add the following command
/usr/local/nginx/sbin/nginx start

If you find that the self-starting script is not executed after booting, you have to confirm whether the access permission of the file rc.local is executable, because rc.local is not executable by default. Modify rc.local access permissions and increase executable permissions:

chmod +x /etc/rc.d/rc.local

Operation and maintenance##

Service Management###

# start up
/usr/local/nginx/sbin/nginx
# Reboot
/usr/local/nginx/sbin/nginx -s reload
# Shutdown process
/usr/local/nginx/sbin/nginx -s stop
# Close nginx smoothly
/usr/local/nginx/sbin/nginx -s quit
# Check the installation status of nginx,
/usr/local/nginx/sbin/nginx -V 

Turn off the firewall, or add firewall rules to test

service iptables stop

Or edit the configuration file:

vi /etc/sysconfig/iptables

Add such a rule to open port 80 and save it:

- A INPUT -m state --state NEW -m tcp -p tcp --dport 80-j ACCEPT

Restart the service to:

service iptables restart
# Command to view the current nat
iptables -t nat -L

Restart the service firewall error resolution###

service iptables restart
# Redirecting to /bin/systemctl restart  iptables.service
# Failed to restart iptables.service: Unit iptables.service failed to load: No such file or directory.

In CentOS 7 or RHEL 7 or Fedora, the firewall is managed by firewalld. Of course, you can restore the traditional management method. Or use new commands for management. If you use the traditional, please execute the following command:

# Traditional command
systemctl stop firewalld
systemctl mask firewalld
# Install command
yum install iptables-services
systemctl enable iptables 
service iptables restart

nginx uninstall##

If you install via yum, use the following command to install.

yum remove nginx

Compile and install, and delete the /usr/local/nginx directory. If the auto-start script is configured, it also needs to be deleted.

Parameter Description##

Nginx installation path. If not specified, the default is/usr/local/nginx。

Configuration##

In Centos, the default configuration file is in /usr/local/nginx-1.5.1/conf/nginx.conf We need to configure some files here. nginx.conf is the main configuration file, composed of several parts, each brace {} represents a part. Each line of instruction ends with a semicolon ;, marking the end of a line.

Commonly used regular

Regular Description Regular Description
. Match any character except the newline character $ match the end of the string
? Repeat 0 or 1 times {n} Repeat n times
+ Repeat 1 or more times {n,} Repeat n or more times
* Repeat 0 or more times [c] match a single character c
\ d match numbers [az] match any one of az lowercase letters
^ Match the beginning of the string - -

Global variables###

Variable description variable description
$args This variable is equal to the parameters in the request line, the same as $query_string $remote_port port of the client.
$content_length Content-length field in the request header. $remote_user User name that has been verified by Auth Basic Module.
$content_type Content-Type field in the request header. $request_filename The file path of the current request, generated by root or alias command and URI request.
$document_root The value specified in the root directive for the current request. $scheme HTTP method (such as http, https).
$host Request the host header field, otherwise the server name. $server_protocol The protocol used by the request, usually HTTP/1.0 or HTTP/1.1.
$http_user_agent client agent information $server_addr server address, this value can be determined after completing a system call.
$http_cookie client cookie information $server_name server name.
$limit_rate This variable can limit the connection rate. $server_port The port number of the request to reach the server.
$request_method The action requested by the client, usually GET or POST. $request_uri The original URI containing the request parameters, without the host name, such as: /foo/bar.php?arg=baz.
$remote_addr The IP address of the client. $uri The current URI without request parameters. $uri does not contain the host name, such as /foo/bar.html.
$document_uri Same as $uri. - -

For example request: http://localhost:3000/test1/test2/test.php

$host:localhost
$server_port:3000
$request_uri:/test1/test2/test.php
$document_uri:/test1/test2/test.php
$document_root:/var/www/html
$request_filename:/var/www/html/test1/test2/test.php

Symbol reference

Symbol Description Symbol Description Symbol Description
k,K kilobytes m,M megabytes ms milliseconds
s second m minute h hour
d day w week M one month, 30 days

For example, "8k" and "1m" represent the byte count.
For example, "1h 30m", "1y 6M". Represents "1 hour and 30 minutes", "1 year and 6 months".

Configuration file###

The configuration system of nginx consists of a main configuration file and other auxiliary configuration files. These configuration files are all plain text files, all located in the conf directory under the nginx installation directory.

Instructions are provided by various modules of nginx, and different modules provide different instructions to implement configuration. In addition to the form of Key-Value commands, there are also scope commands.

The configuration information in nginx.conf is classified according to its logical meaning, which is divided into multiple scopes, or called configuration instruction context. Different scopes contain one or more configuration items.

The following context instructions are more used:

Directive Description Contains Directive
The parameters of main nginx that have nothing to do with specific business functions (such as http service or email service proxy) at runtime, such as the number of work processes, running identity, etc. user, worker_processes, error_log, events, http, mail
http Some configuration parameters related to providing http services. For example: whether to use keepalive, whether to use gzip for compression, etc. server
Several virtual hosts are supported on server http service. Each virtual host has a corresponding server configuration item, which contains the configuration related to the virtual host. When providing a proxy for the mail service, several servers can also be established. Each server is distinguished by the address it listens on. listen, server_name, access_log, location, protocol, proxy, smtp_auth, xclient
In the location http service, a series of configuration items corresponding to certain specific URLs. index, root
mail When implementing email-related SMTP/IMAP/POP3 proxy, some shared configuration items (because it is possible to implement multiple proxies and work on multiple listening addresses). server, http, imap_capabilities
include In order to enhance the readability of the configuration file, so that part of the configuration file can be reused. -
valid_referers Used to verify whether the Http request header Referer is valid. -
try_files is used in the server part, but the most common is still used in the location part, it will try according to the given parameter order, and the first one that is matched will be used. -
if When using the if instruction in the location block, in some cases it does not work as expected, generally avoid using the if instruction. -

For example, we quote two configurations in nginx.conf, vhost/example.com.conf and vhost/gitlab.com.conf. They are all placed under a new directory vhost that I created. The nginx.conf configuration is as follows:

worker_processes  1;
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;        
  location /{            
   root   html;            
   index  index.html index.htm;}        
  error_page   500502503504/50x.html;        
  location =/50x.html {            
   root   html;}}    
 include  vhost/example.com.conf;    
 include  vhost/gitlab.com.conf;}

Simple configuration: example.com.conf

server {    
 # Listening port 80
 listen       80;    
 server_name  baidu.com app.baidu.com; #Specify the domain name here
 index        index.html index.htm;    #Specify the default entry page here
 root /home/www/app.baidu.com;         #Specify the directory here
}

Built-in predefined variables###

Nginx provides many predefined variables, which can also be set by using set. You can use predefined variables in the if, or you can pass them to the proxy server. The following are some common predefined variables, see more

Variable name value
$args_name name parameter in the request
$args All request parameters
$query_string alias of $args
$content_length Request header Content-Length value
$content_type Request header Content-Type value
$host If there is a Host, it is the value of the request header Host; if there is no such header, the value is equal to the value of the server_name matching the request
$remote_addr Client's IP address
$request The complete request, received from the client, including Http request method, URI, Http protocol, header, request body
$request_uri The complete request URI, the request from the client, including parameters
$scheme The currently requested protocol
$uri Standardized URI of the current request

Reverse proxy###

A reverse proxy is a Web server that accepts client connection requests, then forwards the request to the upstream server, and returns the results obtained from the server to the connected client. The following simple reverse proxy example:

server {  
 listen       80;                                                        
 server_name  localhost;                                              
 client_max_body_size 1024M;  #Maximum number of single file bytes allowed by the client

 location /{    
 proxy_pass                         http://localhost:8080;    
 proxy_set_header Host              $host:$server_port;    
 proxy_set_header X-Forwarded-For   $remote_addr; #The real IP of the HTTP requester
 proxy_set_header X-Forwarded-Proto $scheme;      #In order to correctly identify whether the protocol sent by the actual user is http or https
  }}

Complex configuration: gitlab.com.conf.

server {    
 # Listening port 80
 listen       80;    
 server_name  git.example.cn;    
 location /{        
  proxy_pass   http://localhost:3000;        #The following are some reverse proxy configurations that can be deleted
  proxy_redirect             off;        #The back-end web server can pass X-Forwarded-For obtaining user's real IP
  proxy_set_header           Host $host;        
  client_max_body_size       10m; #Maximum number of single file bytes allowed by the client
  client_body_buffer_size    128k; #The maximum number of bytes requested by the buffer agent to buffer the client
  proxy_connect_timeout      300; #Nginx connects to the backend server timeout time(Agent connection timed out)
  proxy_send_timeout         300; #Backend server data return time(Proxy sending timeout)
  proxy_read_timeout         300; #After a successful connection, the back-end server response time(Proxy receiving timeout)
  proxy_buffer_size          4k; #Set the buffer size of the proxy server (nginx) to save user header information
  proxy_buffers              4 32k; #proxy_buffers, if the average web page is below 32k, set this way
  proxy_busy_buffers_size    64k; #Buffer size under high load (proxy_buffers*2)
    }}

In the configuration of proxy to the upstream server, the most important thing is the proxy_pass instruction. The following are some common instructions in the proxy module:

Instructions Description
proxy_connect_timeout The longest waiting time of Nginx from accepting the request to connecting to the upstream server
proxy_send_timeout Backend server data return time (Proxy sending timeout)
proxy_read_timeout After a successful connection, the back-end server response time (proxy receiving timeout)
proxy_cookie_domain Replace the domain attribute of the Set-Cookie header from the upstream server
proxy_cookie_path Replace the path attribute of the Set-Cookie header from the upstream server
proxy_buffer_size Set the buffer size of the proxy server (nginx) for storing user header information
proxy_buffers proxy_buffers buffer, the average webpage is below k
proxy_set_header Rewrite the content of the header sent to the upstream server, or it can be achieved by setting the value of a header to an empty string instead of sending a header
proxy_ignore_headers This directive prohibits the processing of responses from proxy servers.
proxy_intercept_errors Make nginx block the response with HTTP response code 400 or higher.

Load Balancing###

The upstream directive enables a new configuration section in which a group of upstream servers are defined. These servers may be set with different weights, or they may be marked as down for server maintenance.

upstream gitlab {
 ip_hash;    #For upstream load balancing, weight is the weight, which can be defined according to the machine configuration. The weigth parameter represents the weight, the higher the weight, the greater the probability of being assigned.
 server 192.168.122.11:8081;    
 server 127.0.0.1:82 weight=3;    
 server 127.0.0.1:83 weight=3 down;    
 server 127.0.0.1:84 weight=3; 
 max_fails=3  fail_timeout=20s;    
 server 127.0.0.1:85 weight=4;;    
 keepalive 32;}
server {    
 # Listening port 80
 listen       80;    
 server_name  git.example.cn;    
 location /{        
  proxy_pass   http://gitlab;    #Set up a proxy here, with the same name as upstream
  # The following are some reverse proxy configurations that can be deleted
  proxy_redirect             off;        #The back-end web server can pass X-Forwarded-For obtaining user's real IP
  proxy_set_header           Host $host;        
  proxy_set_header           X-Real-IP $remote_addr;        
  proxy_set_header           X-Forwarded-For $proxy_add_x_forwarded_for;        
  client_max_body_size       10m;  #Maximum number of single file bytes allowed by the client
  client_body_buffer_size    128k; #The maximum number of bytes requested by the buffer agent to buffer the client
  proxy_connect_timeout      300;  #Nginx connects to the backend server timeout time(Agent connection timed out)
  proxy_send_timeout         300;  #Backend server data return time(Proxy sending timeout)
  proxy_read_timeout         300;  #After a successful connection, the back-end server response time(Proxy receiving timeout)
  proxy_buffer_size          4k; #Set the buffer size of the proxy server (nginx) to save user header information
  proxy_buffers              4 32k;#Buffer, if the average web page is below 32k, set this
  proxy_busy_buffers_size    64k; #Buffer size under high load (proxy_buffers*2)
  proxy_temp_file_write_size 64k; #Set the size of the cache folder, greater than this value, will be uploaded from the upstream server
    }}

Each request is allocated to different back-end servers one by one in chronological order. If the back-end server is down, it can be automatically eliminated.

Load balancing:

The upstream module can use three load balancing algorithms: polling, IP hashing, and minimum connections.

Polling: By default, the polling algorithm is used, and no configuration instructions are required to activate it. It is based on the principle of who is next in the queue to ensure that access is evenly distributed to each upstream server;
IP hash: Activate through the ip_hash command. Nginx uses the first 3 bytes of the IPv4 address or the entire IPv6 address as a hash key. The same IP address can always be mapped to the same upstream server;
Minimum number of connections: Activate by least_conn instruction, the algorithm selects an upstream server with the least number of active connections to connect. If the upstream server has different processing capabilities, it can be explained by configuring the weight for the server. The algorithm will take into account the weighted minimum number of connections of different servers.

RR

Simple configuration, here I have configured 2 servers, of course, it is actually one, but the port is different, and the 8081 server does not exist, that is to say, it is not accessible, but we visit http://localhost. If the server is not accessible (the server is hung up), it will not jump if the server is inaccessible (the server is hung up). It will jump to http://localhost:8080 by default. To this server, it also avoids the situation that a server hangs and affects the use. Since Nginx defaults to the RR strategy, we do not need other more settings

upstream test {    
 server localhost:8080;    
 server localhost:8081;}
server {    
 listen       81;    
 server_name  localhost;    
 client_max_body_size 1024M; 
 location /{        
  proxy_pass http://test;        
  proxy_set_header Host $host:$server_port;}}

The core code of load balancing is

upstream test {    
 server localhost:8080;    
 server localhost:8081;}

Weights####

Specify the polling probability, the weight is proportional to the access ratio, and is used in the case of uneven back-end server performance. E.g

upstream test {    
 server localhost:8080 weight=9;    
 server localhost:8081 weight=1;}

Then 10 times, generally only 1 time will visit 8081, and 9 times will visit 8080

ip_hash

The above two methods have a problem, that is, the request may be distributed to another server when the next request comes. When our program is not stateless (using session to save data), there is a big problem at this time This is very problematic. For example, if you save the login information in the session, you need to log in again when you jump to another server. So many times we need a client to access only one server, then we need to use iphash, iphash Each request is allocated according to the hash result of the access ip, so that each visitor has fixed access to a back-end server, which can solve the session problem.

upstream test {    
 ip_hash;    
 server localhost:8080;    
 server localhost:8081;}

fair

This is a third-party module that allocates requests according to the response time of the back-end server, and priority is given to the short response time.

upstream backend {
 fair;    
 server localhost:8080;    
 server localhost:8081;}

url_hash

This is a third-party module that distributes requests according to the hash result of the access URL, so that each URL is directed to the same back-end server, which is more effective when the back-end server is cached. Add a hash statement in the upstream, and other parameters such as weight cannot be written in the server statement. hash_method is the hash algorithm used

upstream backend {    
 hash $request_uri;    
 hash_method crc32;    
 server localhost:8080;    
 server localhost:8081;}

The above five types of load balancing are applicable to different situations, so you can choose which strategy mode to use according to the actual situation, but fair and url_hash need to install third-party modules to use

Server command optional parameters:

  1. weight: Set the access weight of a server. The higher the value, the more requests will be received;
  2. fail_timeout: The server must provide a response within this specified time. If no response is received within this time, the server will be marked as down;
  3. max_fails: Set the maximum number of attempts to connect to a server within the fail_timeout time. If this number is exceeded, the server will be marked as down;
  4. down: mark a server no longer accepting any requests;
  5. backup: Once other servers are down, the machine with this mark will receive the request.

keepalive instruction:

The Nginx server will maintain a connection with the upstream server for each worker.

Block ip

Add the following configuration to the nginx configuration file nginx.conf, which can be placed in the http, server, location, limit_except statement block. Pay attention to the relative path. In this example, nginx.conf and blocksip.conf are in the same Directory.

include blockip.conf;

Enter the content in blockip.conf, such as:

deny 165.91.122.67;
deny IP;   #Block single IP access
allow IP;  #Allow single ip access
deny all;  #Block all IP access
allow all; #Allow all ip access
deny 123.0.0.0/8   #Block the entire segment from 123.0.0.1 to 123.255.255.254 access commands
deny 124.45.0.0/16 #Block IP segment from 123.45.0.1 to 123.45.255.254 access commands
deny 123.45.6.0/24 #Block IP segment from 123.45.6.1 to 123.45.6.254 access commands
# If you want to implement such an application, except for a few IPs, all others are rejected
allow 1.1.1.1; 
allow 1.1.1.2;deny all;

Third-party module installation method##

. /configure --prefix=/Your installation directory--add-module=/Third-party module catalog

Redirect##

Redirect the entire site###

server {    
 server_name old-site.com
 return301 $scheme://new-site.com$request_uri;}

Redirect single page###

server {    
 location =/oldpage.html {return301 http://example.org/newpage.html;}}

Redirect the entire subpath###

location /old-site {    
 rewrite ^/old-site/(.*) http://example.org/new-site/$1 permanent;}

performance##

Content Cache###

Allows the browser to cache static content essentially permanently. Nginx will set Expires and Cache-Control header information for you.

location /static{    
 root /data;    
 expires max;}

If you require the browser to never cache the response (for example for tracking requests), use -1.

location =/empty.gif {    
 empty_gif;    
 expires -1;}

Gzip compression###

gzip  on;
gzip_buffers 16 8k;
gzip_comp_level 6;
gzip_http_version 1.1;
gzip_min_length 256;
gzip_proxied any;
gzip_vary on;
gzip_types
 text/xml application/xml application/atom+xml application/rss+xml application/xhtml+xml image/svg+xml
 text/javascript application/javascript application/x-javascript
 text/x-json application/json application/x-web-app-manifest+json
 text/css text/plain text/x-component
 font/opentype application/x-font-ttf application/vnd.ms-fontobject
 image/x-icon;
gzip_disable  "msie6";

Open file cache###

open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;

SSL cache###

ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

Upstream Keepalive

upstream backend {    
 server 127.0.0.1:8080;    
 keepalive 32;}
server {...    
 location /api/{        
  proxy_pass http://backend;        
  proxy_http_version 1.1;        
  proxy_set_header Connection "";}}

monitor###

Use ngxtop to parse nginx access logs in real time, and output the processing results to the terminal, similar to the system command top. All examples read the access log location and format of the nginx configuration file. If you want to specify the access log file and/or log format, use the -f and -a options.

Note: In the nginx configuration, the /usr/local/nginx/conf/nginx.conf log file must be an absolute path.

# Install ngxtop
pip install ngxtop
# Real-time status ngxtop
# The path of the first 10 requests with status 404:

ngxtop top request_path --filter 'status == 404'
# Send the top 10 requests with the most total bytes
ngxtop --order-by 'avg(bytes_sent) * count'
# Top ten IPs, for example, who attacked you the most
ngxtop --group-by remote_addr
# Print requests with 4xx or 5xx status, as well as status and http referer
ngxtop -i 'status >= 400' print request status http_referer
# The average body bytes sent by 200 request path responses'foo'Start:
ngxtop avg bytes_sent --filter 'status == 200 and request_path.startswith("foo")'
# Use the "common" log format to analyze apache access logs from remote machines
ssh remote tail -f /var/log/apache2/access.log | ngxtop -f common

Common usage scenarios##

Cross-domain issues###

In work, sometimes some interfaces do not support cross-domain. At this time, you can simply add add_headers to support cors cross-domain. The configuration is as follows:

server {  
 listen 80;  
 server_name api.xxx.com;    
 add_header 'Access-Control-Allow-Origin''*';  
 add_header 'Access-Control-Allow-Credentials''true';  
 add_header 'Access-Control-Allow-Methods''GET,POST,HEAD';  
 location /{    
  proxy_pass http://127.0.0.1:3000;    
  proxy_set_header X-Real-IP $remote_addr;    
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;    
  proxy_set_header Host  $http_host;}}

Change the header information above, and there is another way to use the rewrite command to redirect the URI to solve the cross-domain problem.

upstream test {  
 server 127.0.0.1:8080;  
 server localhost:8081;}
server {  
 listen 80;  
 server_name api.xxx.com;  
 location /{ 
 root  html;                   #Go request../Files in the html folder
 index  index.html index.htm;  #Homepage response address
  }  
 # Used to intercept requests and match any/api/The address at the beginning,
 # After the match is matched, stop searching for regular.
 location ^~/api/{ 
 # Represents rewriting to intercept incoming requests, and can only work on the string after the domain name except for the passed parameters.
 # For example www.a.com/proxy/api/msg?meth=1&par=2 rewrite, only/proxy/api/msg rewrite.
 # The parameter after rewrite is a simple regular^/api/(.*)$,
 # $1 represents the first one in the regular(),$2 represents the second()The value of, and so on.
 rewrite ^/api/(.*)$ /$1break;    
 # Proxy requests to other hosts
 # Where http://www.b.com/Writing and http://www.b.The difference in com writing is as follows
 # If your request address is his http://server/html/test.jsp
 # Configuration one: http://www.b.com/Followed by "/” 
 #   Reverse proxy into http://www.b.com/html/test.jsp access
 # Configuration one: http://www.b.There is no "/” 
 #   Reverse proxy into http://www.b.com/test.jsp access
 proxy_pass http://test;    #If proxy_pass URL is http://a.xx.com/platform/This situation
 # proxy_cookie_path should be set to/platform//(Note the space between the two slashes)。
 proxy_cookie_path /platfrom/ /;    # http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass_header
 # Set the Cookie header through
 proxy_pass_header Set-Cookie;}}

Jump to the domain with www###

server {    
 listen 80;    
 # Configure the normal domain name with www
 server_name www.wangchujiang.com;    
 root /home/www/wabg/download;    
 location /{        
 try_files $uri $uri//index.html =404;}}
server {    
 # This should be placed below,
 # Wangchujiang without www.com is permanently redirected to https://www.wangchujiang.com
 server_name wangchujiang.com;    
 rewrite ^(.*) https://www.wangchujiang.com$1 permanent;}

Proxy forwarding###

upstream server-api{    
 # api proxy service address
 server 127.0.0.1:3110;}
upstream server-resource{    
 # Static resource proxy service address
 server 127.0.0.1:3120;}
server {    
 listen       3111;    
 server_name  localhost;      #Specify the domain name here
 root /home/www/server-statics;    #Reverse proxy matching api route to API service
 location ^~/api/{        
 rewrite ^/(.*)$ /$1break;        
 proxy_pass http://server-api;}   
 # Assuming that the verification code is also in the API service
 location ^~/captcha {        
 rewrite ^/(.*)$ /$1break;        
 proxy_pass http://server-api;}    
 # Suppose your image resources are all on another service
 location ^~/img/{        
  rewrite ^/(.*)$ /$1break;        
  proxy_pass http://server-resource;}    
 # The routing is on the front-end, there is no real routing on the back-end, and the page with 404 status where the routing does not exist is returned/index.html
 # This method uses scenarios, when you write React or Vue projects, there is no real routing
 location /{        
  try_files $uri $uri//index.html =404;
  #        ^ Spaces are important
    }}

Proxy forwarding connection replacement

location ^~/api/upload {    
 rewrite ^/(.*)$ /wfs/v1/upload break;
 proxy_pass http://wfs-api;}

ssl configuration###

Hypertext Transfer Protocol Secure (abbreviation: HTTPS, English: Hypertext Transfer Protocol Secure) is a combination of Hypertext Transfer Protocol and SSL/TLS to provide encrypted communication and authentication of network server identity. HTTPS connections are often used for transaction payments on the World Wide Web and the transmission of sensitive information in corporate information systems. HTTPS should not be confused with the Secure Hypertext Transfer Protocol (S-HTTP) defined in RFC 2660. HTTPS is currently the first choice for all privacy and security-focused websites. With the continuous development of technology, HTTPS websites are no longer the patents of large websites. All ordinary personal webmasters and blogs can build a secure encrypted website by themselves. website.

Create SSL certificate, if you buy the certificate, you can download it directly

sudo mkdir /etc/nginx/ssl
# Create an SSL key key and X509 certificate file with a validity period of 100 years and an encryption strength of RSA2048.

sudo openssl req -x509 -nodes -days 36500-newkey rsa:2048-keyout /etc/nginx/ssl/nginx.key -out /etc/nginx/ssl/nginx.crt
# For the above command, there will be the following content to be filled in Country Name(2 letter code)[AU]:US
State or Province Name(full name)[Some-State]:New York
Locality Name(eg, city)[]:New York City
Organization Name(eg, company)[Internet Widgits Pty Ltd]:Bouncy Castles, Inc.
Organizational Unit Name(eg, section)[]:Ministry of Water Slides
Common Name(e.g. server FQDN or YOUR name)[]:your_domain.com
Email Address []:admin@your_domain.com

Create a self-signed certificate

First, create a directory of certificates and private keys
# mkdir -p /etc/nginx/cert# cd /etc/nginx/cert

Create a server private key, the command will ask you to enter a password:
# openssl genrsa -des3 -out nginx.key 2048

Create a certificate for signing request (CSR):
# openssl req -new-key nginx.key -out nginx.csr

Remove the necessary password when loading Nginx with SSL support and using the above private key:
# cp nginx.key nginx.key.org

# openssl rsa -in nginx.key.org -out nginx.key

Finally, mark the certificate using the above private key and CSR:
# openssl x509 -req -days 365-in nginx.csr -signkey nginx.key -out nginx.crt

View current nginx compilation options

sbin/nginx -V

Output the following content

nginx version: nginx/1.7.8
built by gcc 4.4.720120313(Red Hat 4.4.7-4)(GCC)
TLS SNI support enabled
configure arguments:--prefix=/usr/local/nginx-1.7.8--with-http_ssl_module --with-http_spdy_module --with-http_stub_status_module --with-pcre

If the dependent module does not exist, you can enter the installation directory and enter the following command to recompile and install.

. /configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module

After running, you need make (not make install)

# Backup nginx binary files
cp -rf /usr/local/nginx/sbin/nginx  /usr/local/nginx/sbin/nginx.bak
# Overwrite nginx binary files
cp -rf objs/nginx   /usr/local/nginx/sbin/

HTTPS server

server {    
 listen       443 ssl;    
 server_name  localhost;    
 ssl_certificate /etc/nginx/ssl/nginx.crt;    
 ssl_certificate_key /etc/nginx/ssl/nginx.key;    
 # Prohibit the server version in the header to prevent hackers from exploiting version vulnerabilities
 server_tokens off;   
 # Set up ssl/The type and size of the tls session cache. If this parameter is set, it is generally shared, and buildin may parameter memory fragmentation. The default is none, which is similar to off, and cache is disabled. Such as shared:SSL:10m means that all my nginx worker processes share the ssl session cache. According to the official website, 1M can store about 4000 sessions.
 ssl_session_cache    shared:SSL:1m; 

 # The client can reuse the expiration time of the ssl parameter in the session cache. The default 5 minutes of the intranet system is too short, and it can be set to 30m, that is, 30 minutes or even 4h.
 ssl_session_timeout  5m; 

 # Choose an encryption suite, the suite (and order) supported by different browsers may be different.
 # The wording specified here is recognized by the OpenSSL library, you can use openssl-v cipher 'RC4:HIGH:!aNULL:!MD5'(Following is the package encryption algorithm you specified) Let's see the supported algorithms.
 ssl_ciphers  HIGH:!aNULL:!MD5;    
 # When setting the negotiated encryption algorithm, give priority to using the encryption suite of our server instead of the encryption suite of the client browser.
 ssl_prefer_server_ciphers  on;    
 location /{        
 root   html;        
 index  index.html index.htm;}}

Force http redirect to https

server {    
 listen       80;    
 server_name  example.com;    
 rewrite ^ https://$http_host$request_uri? permanent;    
 # Force redirect http to https
 # Enable or disable the emission of nginx version in error page and "server" response header fields. Prevent hackers from exploiting version vulnerabilities
 server_tokens off;}

Two virtual hosts###

Pure static-html support

http {    
 server {        
  listen          80;        
  server_name     www.domain1.com;        
  access_log      logs/domain1.access.log main;
  location /{            
  index index.html;            
  root  /var/www/domain1.com/htdocs;}}    
 server {        
  listen          80;        
  server_name     www.domain2.com;        
  access_log      logs/domain2.access.log main;
  location /{            
  index index.html;            
  root  /var/www/domain2.com/htdocs;}}}

Virtual host standard configuration###

http {  
 server {    
 listen          80default;
 server_name     _ *;
 access_log      logs/default.access.log main;
 location /{       
  index index.html;
  root  /var/www/default/htdocs;}}}

Anti-theft chain###

location ~* \.(gif|jpg|png|swf|flv)$ {
 root html
 valid_referers none blocked *.nginxcn.com;if($invalid_referer){
  rewrite ^/ www.nginx.cn       
  # return404;}}

Virtual directory configuration###

The directory specified by alias is accurate, root is the parent directory of the specified directory, and the parent directory must contain the directory with the same name specified by location.

location /img/{    
 alias /var/www/image/;}
# access/img/Files in the directory, ningx will automatically go/var/www/image/Directory to find files

location /img/{    
 root /var/www/image;}
# access/img/Files under the directory, nginx will go/var/www/image/img/Find the file in the directory.]

Anti-theft diagram configuration###

location ~ \/public\/(css|js|img)\/.*\.(js|css|gif|jpg|jpeg|png|bmp|swf){
 valid_referers none blocked *.jslite.io;if($invalid_referer){        
  rewrite ^/  http://wangchujiang.com/piratesp.png;}}

Block .git and other files###

location ~(.git|.gitattributes|.gitignore|.svn){
 deny all;}

The domain name path can be accessed normally with or without the need

http://wangchujiang.com/api/index.php?a=1&name=wcj
         ^ With suffix

http://wangchujiang.com/api/index?a=1&name=wcj
         ^ No suffix

The rules of nginx rewrite are as follows:

rewrite ^/(.*)/$ /index.php?/$1 permanent;if(!-d $request_filename){set $rule_1 1$rule_1;}if(!-f $request_filename){set $rule_1 2$rule_1;}if($rule_1 ="21"){ 
 rewrite ^//index.php last;}

Error problem##

The plain HTTP request was sent to HTTPS port

The solution, fastcgi_param HTTPS $https if_not_empty add this rule,

server {    
 listen 443 ssl; #Pay attention to this rule
 server_name  my.domain.com;    
 fastcgi_param HTTPS $https if_not_empty; 
 fastcgi_param HTTPS on;    
 ssl_certificate /etc/ssl/certs/your.pem;
 ssl_certificate_key /etc/ssl/private/your.key;
 location /{
  # Your config here...}}

Recommended Posts

CentOS7 installation and maintenance of nginx from entry to master
From installation to entry of FastDFS under Centos7
CentOS7 installation and maintenance of Gitlab
Centos7 installation of PHP and Nginx tutorial detailed
Centos7 installation and configuration of Jenkins
Centos6.5 installation and deployment of KVM
Introduction to CentOS7 installation process of openjdk, tomcat and mysql
Installation and use of Mysql under CentOS
Centos-6.5 installation and deployment of LNMP environment
Installation and configuration of redis under centos7
Centos7 installation and deployment of gitlab server
Installation and deployment of Nginx in Ubuntu
Centos7 installation and deployment of Airflow detailed
Installation and configuration of JDK in CentOS 7 system
Installation and configuration of rsync server under CentOS 6.5
Installation and configuration of CentOS 7 in VMware Workstation
Graphical installation of CentOS8
Installation and cracking of confluence6.3 operation records under Centos
Installation and cracking of Jira7 operation records under Centos
Centos mysql installation and configuration
CentOs7.3 compile and install Nginx 1.9.9
Centos7 installation and configuration prometheus
Detailed explanation of Spark installation and configuration tutorial under centOS7
CentOS 7 installation and configuration PPTP
CentOS installation and configuration cmake
Centos7.5 installation and configuration MongoDB4.0.4
CentOS 7 installation and configuration PPTP
centos7 kvm installation and use
Centos7 silent installation of Oracle11g
CentOS7 postgresql installation and use
CentOS environment installation of Docker
Centos8 minimal deployment and installation of OpenStack Ussuri detailed tutorial
Centos7 elk7.1.1 installation and use
Linux overview of Python automated operation and maintenance and the ultimate guide to virtual machine installation and use
Ubuntu basic settings: introduction to the installation and use of openssh-server
Server upgrade to centos8 website configuration-php and mysql upgrade from 5.6 to php7 and msyql
Analysis of Hyper-V installation CentOS 8 problem
Use Nginx and u under CentOS
Centos7 installation of Dameng database tutorial
CentOS 8 installation of MariaDB detailed tutorial
Installation under centos6.9 of jenkins learning
Centos7 hadoop cluster installation and configuration
CentOS 6.x compile and install Nginx
How to install Nginx on CentOS 8
CentOS7.2 and Nginx configuration virtual host
CentOS 7.X system installation and optimization
Java-JDK installation and configuration under CentOS
CentOS 7 Tomcat service installation and configuration
001. Installation of enterprise-level CentOS7.6 operating system
Python from entry to proficiency (2): Introduction to Python
CentOS NTP server installation and configuration
Nginx installation and configuration load (ubuntu12.04)
CentOs7 installation and deployment Zabbix3.4 original
2-Kubernetes entry manual installation and deployment
Erlang 20.2 installation and deployment under CentOS 7
Centos7 mysql database installation and configuration
CentOS 7 system installation and configuration graphic tutorial
ubuntu Docker installation and deployment of Rancher
How to verify successful installation of python
Tomcat installation and configuration under CentOS 7 (Tomcat startup)
MySQL 8.0 installation, deployment and configuration under CentOS 6/7