Nginx (Engine X) is a lightweight Web server (software), reverse proxy server (software) and email (IMAP/POP3) proxy server (software).

In our company, the most common scenario for Nginx is to configure domain names, but the term “configuring domain names” is too general and loose. Why is that?

Let’s extend that a little bit and start with domain names.

Domain Name ** is simply a string, such as Baidu.com. Domain names allow you to access a website/site in your browser. IP addresses such as 220.181.38.148 can also be accessed, but 99% of people use domain names because they are much easier to remember.

Technically, a “web site” is software that is deployed on a server, and to access it, the browser must know where the server is. So why does a web browser know which server a web site is on by using a domain name? This brings us to the Domain Name Server (DNS).

As the Name implies, the Domain Name Server (DNS) means Domain Name Server. What DNS does is tell the browser what the IP address of a domain name is.

How does DNS know the mapping between domain names and IP addresses? This involves domain name resolution.

Domain name resolution, for our company, only need to pay attention to one type, is ** “A record” type. A stands for Address. To configure A record, you need to configure the mapping between A domain name and an IP Address **. Many people say “configure domain name”, but his purpose may be to do “domain name resolution”.

** Domain name resolution can be performed in the domain registrar’s management background. ** The main domestic domain name registrars are wanwang (Ali), Xinnet, DNSPod (Tencent), etc., these domain name registrars in addition to providing domain name purchase services, will also provide domain name resolution services, generally in the management background can see the “domain name resolution” function.

Summarize the relevant process of domain name —

  1. Visit a domain registrar’s website to select and purchase a domain name (usually a level 1 domain, such as aaa.com)

  2. After the purchase, log in to the domain registrar management background, find the “domain name resolution” function, and add A domain name resolution A record, usually to resolve the secondary domain name or the corresponding subdomain name, such as 1.aaa.com resolution to A public IP address (for our company’s project, the IP corresponding to the server, Nginx is usually installed, or this IP address corresponds to the hospital firewall server. It allows public network users to access the Nginx server behind the firewall through port mapping.)

What does Nginx have to do with all this domain name stuff?

Simply put, the user accesses the domain name through the browser, just completes the access from the client to the server. After that, Nginx comes in and captures the requests from the public network and forwards them to a back-end server based on configuration rules. After processing the request, the backend server sends the response to the Nginx server. The Nginx server receives the response and sends it back to the user client, thus completing a complete request process. This is a generic interpretation of “reverse proxy”.

Nginx has many advantages, such as high performance (high concurrency support is to force), high scalability, modularity design, the large third-party modules), cross-platform (binary), high reliability, low risk (down), and so on, so familiar with the related function of Nginx is very be necessary, especially for the backend development.

Install Nginx

Developers often ask operations to assign a domain name and then reverse proxy requests for that domain name to a port on a server. What the operation personnel do is to go to DNSPod (A record) and resolve A new domain name to the IP address of the company’s Nginx server (Tencent cloud Nginx server or the company’s internal NETWORK Nginx server). That is, 115.159.1.60 (Tencent cloud) /183.129.254.168 (Intranet), then go to the Nginx server, add a server configuration block to an existing configuration file or directly add a configuration file, and finally reload Nginx.

This approach takes advantage of the company’s existing Nginx to reverse proxy requests. You can do this for some non-saas (standalone) projects, but standalone Nginx has the advantages and necessity of standalone deployment.

Deploying Nginx independently means —

  • Does not occupy the bandwidth resources of the company’s Nginx server

  • An independent project that exclusively uses the bandwidth resources of the local Nginx server

  • To some extent, speed up the service access

Therefore, deploying Nginx independently is a good choice. ** However, the public network bandwidth of the server where Nginx resides must be high enough because all services are accessed through Nginx reverse proxy. ** For corporate projects, it is generally recommended that the bandwidth of the Nginx server be up to 20 MB.

Here’s how to install Nginx on your server (it’s also a good idea to contact your operations staff to install it).

1. Install Nginx on Linux

For independent deployment projects, customers are generally required to provide the CentOS 7.x version of the server (you can enter cat /etc/redhat-release on the server to check the version), so we will explain how to install Nginx on the CentOS 7.x system separately.

A prerequisite for

First, ensure that there is a user who has the root permission of the CentOS server. The sudo command can take effect only for root users.

Second, you need to make sure your CentOS server has access to the public network (mainly to make it easier to install software through YUM), otherwise you have to upload binary source packages for manual compilation, which will most likely fail because you will not be able to resolve complex software dependencies smoothly.

Step 1 — Add the Nginx yum source

$ sudo rpm -ivh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
Copy the code

After installing the yum source, verify that it was added successfully

$ sudo yum repolist
Copy the code

If you see an Nginx repO, the nginx repository was added successfully.

Step 2 — Install Nginx

$ sudo yum -y install nginx
Copy the code

Step 3 — Start Nginx

$ sudo systemctl start nginx
Copy the code

Note that the firewall status of the server is active. If the firewall status is active, you must enable HTTP (port 80 by default) and HTTPS (port 443 by default) services to be accessed.

Check the firewall status (CentOS7 uses firewalld to disable the HTTP service by default)

$ sudo systemctl status firewalld
Copy the code

If running is displayed, the firewall is enabled. Run the following command to enable HTTP and HTTPS services

$ sudo firewall-cmd --permanent --zone=public --add-service=http $ sudo firewall-cmd --permanent --zone=public --add-service=https$ sudo firewall-cmd --reload
Copy the code

Enter the following command to check whether the access to HTTP and HTTPS services is enabled

$ sudo firewall-cmd --list-service
Copy the code

It is OK to see HTTP and HTTPS in the result list.

A few more nginx-related commands.

Set Nginx to boot —

$ sudo systemctl enable nginx
Copy the code

Reload the Nginx configuration

$ sudo systemctl reload nginx
Copy the code

Restart Nginx service —

$ sudo systemctl restart nginx
Copy the code

CentOS 7 SELinux requires network access to use reverse proxy.

2. Install Nginx on Windows

Please note that Nginx officially considers the Windows version of Nginx to be a beta release, so its high performance and scalability cannot be compared to the Linux version.

Step 1 – Download the latest mainline version

The latest mainline version is 1.17.4 and can be downloaded from nginx.org/download/ng… .

Step 2 — Unzip Nginx

We will put the main line version of the compressed package in a directory to decompress, such as the C drive root directory, and then decompress.

Step 3 — Start Nginx

To start nginx, double-click nginx.exe in the nginx-1.17.4 directory.

You can open a CMD window and run the taskList command to see if Nginx starts properly, for example —

C:\nginx-1.17.4> taskList /fi "imagename eq nginx.exe"Image Name PID Session Name Session# Mem Usage=============== ======== ============== ========== ============nginx.exe 652 Console 0 2 780 Knginx.exe 1332 Console 0 3 112 KCopy the code

The above one is the master process and the other is the worker process.

If the nginx.exe process is not displayed, go to the logs directory in the nginx-1.17.4 directory and check the error. Log file.

Note that the Nginx run directory, such as C:\nginx-1.17.4, is the directory prefix of the relative path configured in the Nginx configuration file (Nginx configuration file is C:\nginx-1.17.4\conf\nginx.conf).

However, nginx started by double-clicking nginx.exe is only a console application, not a system service, which means that once the CMD window is closed, the Nginx process stops. Of course, if the server unexpectedly shuts down, Nginx is not running after the restart.

So we had to find a way to package it as a system service, so that we could set it up to start up, and also easily restart or stop the service.

We use the open source Windows Service Wrapper software or NSSM to wrap Nginx as a Windows system Service. By the way, winSW can also wrap Java JAR packages (such as a Spring Boot JAR package) as Windows system services.

Specific steps:

  1. Download the official WinSW software, the latest version of V2.3.0. Winsw requires.NET support (that is, the Server must have.net library). For Windows Server 2008 R2, download WinSW.NET4.exe.

  2. Put WinSW.NET4.exe in the Nginx run directory, such as C:\nginx-1.17.4. For convenience, rename WinSW.NET4.exe to nginx-service.exe. In this directory, create an XML file with the same name, that is, nginx-service.xml. In other words, the full path of nginx-service.exe is C:\nginx-1.17.4\nginx-service.exe, The full path to nginx-service-xml is C:\nginx-1.17.4\nginx-service.xml.

  3. CMD to kill the nginx process in C:\nginx-1.17.4. Create a CMD file named nginx-stop. CMD

    @echo off​cd /C %~dp0​if not exist logs\nginx.pid GOTO skipnginx.exe -s quitdel logs\nginx.pid​:skip​taskkill /f /IM nginx.exe
    Copy the code
  4. Edit the contents of the nginx-service. XML file as follows

    <? The XML version = "1.0" encoding = "utf-8"? ><service> <id>Nginx Service</id> <name>Nginx Service</name> <description>High Performance Nginx Service</description> < the logpath > C: \ nginx - 1.17.4 \ logs < / logpath > < log mode = "roll - by - size" > < sizeThreshold > 10240 < / sizeThreshold > 8 < / keepFiles < keepFiles > > < / log > < the executable > C: \ nginx - 1.17.4 \ nginx exe < / the executable > The < stopexecutable > C: \ nginx - 1.17.4 \ nginx - stop. CMD < / stopexecutable > < / service >Copy the code
  5. Then open a CMD window as administrator and switch to the C:\nginx-1.17.4 directory.

  6. Run the nginx-service.exe install command to register the nginx service.

  7. Press Win +R and enter services. MSC to open the Windows system Service list, find the Nginx Service, right click Start, and click the Properties menu to set the startup type to “Automatic” to complete the setting of the Service.

Configure Nginx

The global configuration file path for Nginx installed on CentOS is /etc/nginx/nginx.conf. However, this global configuration file is generally used to configure Nginx process users, Nginx worker_processes, and so on. It is not necessary for developers to modify it.

Developers, generally only need to pay attention to the/etc/nginx/conf. D/default. Conf and/etc/nginx/conf., d/a custom. The conf file, etc. The *. Conf file we created in conf.d will be loaded as soon as the Nginx service is reloaded (nginx-s reload).

For Windows, we do not customize the *. Conf configuration file. Instead, we directly modify the global configuration file default.conf and append related configuration at the bottom of the file.

Let’s talk about the most common Nginx configurations.

1. Configure the server- reverse proxy

The server block configuration is arguably the most used configuration for operations and developers. We often say do a domain name configuration, virtual host configuration, service reverse proxy configuration, is to add a server block configuration.

For example, we in the conf. D directory to create a hlwyy. Conf configuration files, command is vi/etc/nginx/conf. D/hlwyy. Conf. Then we press I on the keyboard to enter insert mode.

(1) HTTP reverse proxy configuration

Enter the following command —

server { listen 80; server_name foobar.com; Location / {proxy_pass http://127.0.0.1:8080/; }}Copy the code

After that, press ESC to exit the insert mode, and press :wq to save and exit. In this way, the simplest reverse proxy configuration for HTTP domain name is completed.

Let’s analyze the instructions above.

  1. Server: Needless to say, since write is server, that must be to do the configuration of the service, or is to do the configuration of the virtual host

  2. Listen: specifies the local port that the Nginx service listens on. 80 is the default HTTP port and 443 is the default HTTPS port. Listening on port 80 means listening on HTTP connections

  3. Server_name: indicates a domain name, but rarely an IP address. “foobar.com” indicates a domain name, and the IP address resolved by this domain name is the public IP address of the current Nginx server

  4. Location: Configates the routing rule. This can be followed by a specific URL path or regular expression. / indicates the request matching the project root directory, that is, the request matching the URL foobar.com/

  5. Proxy_pass: specifies which service to reverse proxy the request to. The command above is to reverse proxy the request to foobar.com/ to the service that occupies port 8080 on the host (for our company’s project, it is basically tomcat process). Note that if the Nginx server itself is unable to access the backend server address (in other words, the server on which Nginx is located cannot Telnet 127.0.0.1:8080), then the reverse proxy is disabled or the forward slash at the end of the server address is not written.

Pay attention to Spaces and semicolons to avoid unnecessary Nginx configuration syntax errors.

(2) HTTPS reverse proxy configuration

Let’s look at the simplest HTTPS domain name reverse proxy configuration.

server { listen 443 ssl; server_name foobar.com; ssl_certificate /etc/nginx/ssl/foobar.com.crt; ssl_certificate_key /etc/nginx/ssl/foobar.com.key; # match root URL request location / {proxy_pass http://127.0.0.1:8080/; } # match /admin/ path URL request location /admin/ {proxy_pass http://127.0.0.1:13130/; } # image file stored in the/data/images directory location ~ \. (GIF | JPG | PNG) ${root/data/images; }}Copy the code

Compared with the reverse proxy configuration for HTTP domain names, the reverse proxy configuration for HTTPS domain names has three new instructions.

  1. SSL: follows port 443 monitored by listen. Port 443 is monitored and SSL access is enabled

  2. Ssl_certificate: Nginx SSL certificate files on Linux servers usually end in.crt. The certificate file path can be a relative path, but to reduce unnecessary errors (such as file permissions), please set it to an absolute path. /etc/nginx/ SSL

  3. Ssl_certificate_key: specify the SSL private key file path, Nginx types of SSL private key file, generally is based on the key at the end of the file, also use absolute paths, such as/etc/nginx/ssl/foobar.com.key

Note the configuration of three locations, one matching the URL foobar.com/ and one matching the URL foobar.com/admin/, and Nginx reverse proxy them to different services. The last location is followed by a regular expression (beginning with a ~ symbol) that matches against the re. In the example above, when accessing the URL foobar.com/1.png, Nginx returns the /data/images/1.png image from the server to the requester.