Nginx step learning


Terminal connection to remote server

ssh  [email protected] //Where name refers to the server login user name and IP refers to the server address
ssh [email protected]

Press enter and enter the server password. No accident, you have connected to your server. Next, do whatever you want.

Basic configuration


Nginx direct start

In CentOS 7.4 (not in the lower version), you can directly use nginx to start the service.


Start with systemctl command

You can also use a Linux command to start. I usually use this method. Because this method is the same no matter what service is started, just change the name of the service (without adding additional memory points).

systemctl start nginx.service

After entering the command without any prompt, how do we know where the nginx service has been started? You can use the combined commands of Linux to query the health status of the service.

ps aux | grep nginx

If the startup is successful, similar results will appear as follows.

root     20152  0.0  0.0  46392   976 ?        Ss   13:23   0:00 nginx: master process nginx
nginx    20153  0.0  0.1  46788  2172 ?        S    13:23   0:00 nginx: worker process
root     20221  0.0  0.0 112648   964 pts/0    R+   13:33   0:00 grep --color=auto nginx

These three records show that our nginx is normally turned on.

stop it

Four ways to stop nginx service
There are many methods to stop nginx. Different methods can be adopted according to requirements. Let’s explain them one by one.

  1. Stop service now
nginx  -s stop

This method is relatively tough. It directly stops the process whether it is working or not.

  1. Stop service calmly
nginx -s quit

This method is milder than stop. The process needs to stop after completing the current work.

  1. Kill method kills process

This method is also barbaric. We directly kill the process, but when it has no effect, it is better for us to use this method.

killall nginx
  1. Systemctl stop
systemctl stop nginx.service

Restart the nginx service

Sometimes we need to restart the nginx service. At this time, we can use the following command.

systemctl restart nginx.service

Reload configuration file

After rewriting or modifying the configuration file of nginx, you need to reload. At this time, you can use the command given by nginx.

nginx -s reload

View port number

By default, nginx will listen to port 80 after startup to provide HTTP access. If port 80 has been occupied, the startup will fail. We can use itnetstat -tlnpCommand to view the occupation of the port number.

Customize error pages and access settings

Multiple errors point to one page

You can see the following sentence in / etc / nginx / conf.d/default.conf.

error_page   500 502 503 504  /50x.html;

error_ The page command is used to customize the error page. 500502503504 are the most common error codes in http. The / 50.html command is used to indicate that when any of the above specified errors occurs, they are processed with the / 50.html file in the root directory of the website.

It is the wrong top processing method alone

Sometimes it is necessary to show these error pages separately to give users a better experience. So we need to set a different page for each error code. The setting method is as follows:

error_page 404  /404_error.html;

Then create a new 404 under the website directory_ Error.html file and write some information.

        <meta charset="UTF-8">
        <h1>404 page not found</ h1>

Then restart our service and visit again. You will find that the 404 page has changed.

Replace the error code with an address

When handling errors, you can not only use the resources of this server, but also use external resources. For example, we set the configuration file to this.

error_page  404;

We used the baidu address as a hint that we didn’t find on the 404 page, so we formed it. If we didn’t find the file, we jumped directly to Baidu

Simple access control

Sometimes our server only allows access to specific hosts, such as internal OA system, application management background system, or some application interfaces. At this time, we need to control some IP access. We can directlylocationConfigure in.

You can configure it directly in default.conf.

location / {
    #Inaccessible IP
    #Can access IP
    #Not accessible except allow
    deny   all;

After configuration, restart the server to restrict and allow access. This is very common in work. You must remember it well.

Nginx access details

Instruction priority

Let’s look at the code first:

location / {
    deny   all;

The above configuration indicates that only45.76.202.231For access, other IP addresses are prohibited. But if we putdeny allCommand, move toallow will happen before that? You will find that all IP addresses are not allowed to access.This shows a problem: for two permission instructions in the same block, the first setting will overwrite the later setting (that is, who triggers first and who works).

Complex access control permission matching

In the work, the control requirements of access rights are more complex. For example, the IMG (picture directory) under the website is accessed by all users, but the admin directory under the website only allows internal fixed IP access. At this time, the deny and allow instructions alone cannot be implemented. We need the location block to complete the relevant requirements matching.

location =/img{
    allow all;
location =/admin{
    deny all;

=Number represents exact match, using=After that, the exact matching is carried out according to the subsequent pattern. This is directly related to the security of our website. We must learn

Set access using regular expressions

Only accurate matching can sometimes not complete our work tasks. For example, now we want to prohibit access to all PHP pages. Most PHP pages are background management or interface code. Therefore, in order to be safe, we often prohibit access by all users and only open access within the company.

The code is as follows:

location ~\.php$ {
    deny all;

In this way, we can’t access the files ending in PHP when we visit again. Does it make the website much safer?

Set virtual host

Virtual host refers to dividing multiple disk spaces on a physical host server. Each disk space is a virtual host. Each virtual host can provide external web services without interference with each other. From the outside world, the virtual host is an independent server host, which means that users can use the virtual host to deploy multiple websites with different domain names on the same server without having to buy a server separately for the establishment of a website, which not only solves the problem of maintaining server technology, At the same time, it greatly saves the cost of server hardware and related maintenance costs.

Configuring a virtual host can be based on port number, IP and domain name. In this lesson, we first learn to set a virtual host based on port number.

Configure virtual host based on port number

Configuring the virtual host based on the port number is the simplest way in nginx. The principle is that nginx monitors multiple ports and distinguishes different websites according to different port numbers.

We can configure it directly in the main fileetc/nginx/nginx.confFile or sub configuration fileetc/nginx/conf.d/default.conf。 For the convenience of configuration, I have configured it in the sub file. Of course, you can also create another file, just inconf.dJust under the folder.

Modify the server option in the configuration file, and there will be two servers.

    listen 8001;
    server_name localhost;
    root /usr/share/nginx/html/html8001;
    index index.html;

Compile inusr/share/nginx/html/html8001/Under directoryindex.htmlFile and view the results.

<h1>welcome port 8001</h1>

Finally, access the address and the address with port respectively in the browser. The results are different.

Then we can access it in the browserhttp://

IP based virtual host

IP based and port based configurations are almost the same, except thatserver_nameOption, just configure it as IP.

For example, the above configuration can be modified to:

    listen 80;
    root /usr/share/nginx/html/html8001;
    index index.html;

This requires the support of multiple IPS.

Nginx uses domain names to set up virtual hosts

In the real online environment, a website can be accessed only by domain name and public IP. What we configure most in practice is to set up this virtual host.

Configure virtual hosts divided by domain name

We modifyetc/nginx/conf.dUnder directorydefault.confFile to change the original 80 port virtual host into a virtual host divided by domain name. The code is as follows:

server {
    listen       80;

We will modify the 8001.conf file in the same directory as follows:

        listen 80;
        location / {
            root /usr/share/nginx/html/html8001;
            index index.html index.htm;

Then we use the smooth restart method to restart. At this time, we visit these two web pages in the browser.

In fact, setting the domain name virtual host is also very simple. The main operation is the server of the configuration file_ The name item also needs the cooperation of domain name resolution.

Settings of nginx reverse proxy

The virtual host is completed. As a front-end, one of the necessary skills is reverse proxy. As we all know, our current web model is basically a standard CS structure, that is, client-side to server-side. The proxy is to add a server that provides specific functions between the client side and the server side. This server is what we call the proxy server.

Purpose and benefits of reverse proxy

  • Security: the client of the forward proxy can access any website while hiding its own information, which poses a great threat to the network security proxy. Therefore, we must protect the server. Using the reverse proxy client, users can only access the proxy server through the external network, and users do not know which real server they are accessing, which can provide good security protection.
  • Functionality: the main purpose of reverse proxy is to provide debt balancing, caching and other functions for multiple servers. Load balancing is that the content of a website is deployed on several servers. These machines can be regarded as a cluster. Then nginx can “evenly” distribute the received client requests to all servers in the cluster, so as to realize the equal distribution of server pressure, also known as load balancing.

Simplest reverse proxy

Now we’re going to visithttp://www.suhangweb.comThen reverse proxy tobaidu.comThis website. Let’s go straight toetc/nginx/con.d/8001.confMake changes.

The modified configuration file is as follows:

        listen 80;
        location / {

Generally, our reverse proxy is an IP, but I can proxy a domain name here. In fact, even if our reverse proxy is successful, we can open it in the browserhttp://www.suhangweb.comLet’s test it.

Other reverse proxy instructions

There are also some commonly used instructions for reverse proxy. I’ll list them here:

  • proxy_ set_ Header: change the request header information from the client before sending the client request to the back-end server.
  • proxy_ connect_ Timeout: configure the timeout time when nginx attempts to establish a connection with the back-end proxy server.
  • proxy_ read_ Timeout: configure nginx to wait for the corresponding timeout after sending a read request to the back-end server group.
  • proxy_ send_ Timeout: configure nginx to wait for the corresponding timeout after sending a write request to the back-end server group.
  • proxy_ Redirect: used to modify the location and refresh in the response header returned by the back-end server.

Nginx adapter PC or mobile device

Now many websites have PC and H5 sites, because they can display different pages with better experience according to different customer devices.

Some people say that such needs can be solved with adaptation, such as bootstrap and 24 grid layout, which are really very good schemes, but it is better to write them separately in terms of complexity and ease of use, such as Taobao and JD… These large websites do not adopt adaptation, but use separate production.

How to configure nginx to identify which page should be displayed?

$http_ user_ Use of agent:

Nginx through built-in variables$http_user_agent, you can get the useragent of the requesting client, then you can whether the user is currently in the mobile terminal or the PC terminal, and then display different pages to the user.

The operation steps are as follows:

  1. Create two new folders under / usr / share / nginx /, namely, PC and mobile directories
cd /usr/share/nginx
mkdir pc
mkdir mobile
  1. In the PC and miblic directories, create two new index.html files with the following contents
<h1>I am pc!</h1>
<h1>I am mobile!</h1>
  1. get intoetc/nginx/conf.dIn the directory, modify the 8001.conf file to the following form:
     listen 80;
     location / {
      root /usr/share/nginx/pc;
      if ($http_user_agent ~* '(Android|webOS|ip|iPod|BlackBerry)') {
         root /usr/share/nginx/mobile;
      index index.html;

Gzip compression configuration for nginx

Gzip is a web page compression technology of web pages. After gzip compression, the page size can be changed to 30% or even smaller. Smaller web pages will make users browse better and faster. The implementation of gzip web page compression needs the support of browser and server.

Configuration item for gzip

Nginx provides a special gzip module, and the instructions in the module are very rich

  • Gzip: this command is used to turn on or off the gzip module.
  • gzip_ Buffers: set the system to obtain several units of cache for storing gzip compression result data stream.
  • gzip_ comp_ Level: gzip compression ratio. The compression level is 1-9. The compression level of 1 is the lowest and that of 9 is the highest. The higher the compression level, the greater the compression rate and the longer the compression time.
  • gzip_ Disable: this instruction can be used to disable the compression function for some specific user agents.
  • gzip_ min_ Length: set the minimum number of bytes of the page that can be compressed. The number of page bytes is obtained from the content length of the corresponding message header.
  • gzip_ http_ Version: identifies the HTTP protocol version, which can be 1.1. Or 1.0
  • gzip_ Proxied: used to enable or disable gzip compression of corresponding content received from the proxy server.
  • gzip_ Variable: used to add variable: accept encoding in the response message header to enable the proxy server to identify whether gzip compression is enabled according to the accept encoding in the request header.

Gzip is the simplest configuration

http {
    gzip on;
    gzip_types text/plain application/javascript text/css;

gzip onIs to enable the gizp module. The following line is used to compress the text, JavaScript and CSS files when the client accesses the web page.

After configuration, we can restart the nginx service to make our gizp effective.

If you are a Windows operating system, you can press F12 to open the developer tool, stand-alone the current request, select headers in the tag, and view the HTTP response header information. You can clearly see that content encoding is gzip type.