(Essence) Basic configuration of nginx on August 18, 2020

(Essence) Basic configuration of nginx on August 18, 2020

Install nginx under windows

My local environment: win10-64 bit.

  1. Download nginx
    to the nginx official website to download the corresponding installation package, nginx.org/en/download...

Download and decompress, put the decompressed files in your favorite directory, and place my decompressed files in the root directory of Disk D, as shown in the following figure:

  1. Configuration
    Enter the cmd window of the window, enter the command as shown in the figure below, enter the nginx directory (D:/nginx-1.8.1), use "start nginx.exe" to install nginx, as shown in the following figure:

After the installation is successful, you will see the "nginx.exe" process in the "Task Manager", as shown in the figure below:
Open the Task Manager shortcut key
Method 1: Press continuously in order Hold down the Ctrl, Alt and Delete keys.
Method 2: In the blank space at the bottom of the task bar, right-click to open a menu bar, and click to open the task manager.
Method 3: Ctrl + Shift + Esc key combination, press at the same time, quickly open the task manager to open the shortcut key of the win task manager

One is the main process and the other is the worker process (multiple threads)
. Enter in the browser address bar, and you will see the nginx welcome interface as shown in the figure below

If you find that there is no process, then your installation failed. You can check the error under the logs folder in your D:\nginx-1.8.1 directory.
If you find that it says:

It means that your port 80 is occupied, or the cmd command is executed under dos: netstat -aon | findstr :80 Check whether port 80 is occupied, if it is occupied, then you need to modify the registry, as follows:
1. Open the registry : Regedit
2. Find: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\HTTP
3. Find a REG_DWORD type item Start, change it to 0
4. Restart the system, the System process will not occupy port 80

At this moment, you can execute the
corresponding command again : start nginx.exe command.
nginx.exe -s stop//Stop nginx
nginx.exe -s reload//Reload nginx
nginx.exe -s quit//Exit nginx
Note: In the above command, .exe can be removed, if nginx command is not found, You can add ./before the command,
such as: ./nginx -s reload

Or you can directly use nginx commands by configuring environment variables.
Common nginx commands:
verify that the configuration is correct: nginx -t
view the version number of Nginx: nginx -V
start Nginx: start nginx
quickly stop or close Nginx: nginx -s stop
normally stops Or close Nginx: nginx -s quit
configuration file to modify the reload command: nginx -s reload
How to close Nginx
Two methods
1. Task manager ends the nginx process
2. DOS command nginx -s quit
The operation of the corresponding command is shown in the following figure:

  1. The nginx configuration file
    nginx configuration file is nginx.conf, and the corresponding operations are shown in the following figure:

Nginx configuration file analysis:

Install nginx segmentfault.com/a/119000001 under Mac

What is Nginx?

Nginx is a lightweight web server, reverse proxy and email proxy server. Nginx is specially developed for performance optimization. It is a fast web server that can withstand high load tests.
Source: Nginx (pronounced engine x), it was developed by Russian programmer Igor Sysoev. At first it was used by Russia's large portal and search engine Rambler (Russian: ). This software is issued under the BSD-like protocol and can run on UNIX, GNU/Linux, BSD, Mac OS X, Solaris, and Microsoft Windows operating systems.
When it comes to web servers, Apache server and IIS server are the two giants; but the faster and more flexible opponent: Nginx is catching up.
The application status of Nginx is
in China, and many websites such as Taobao, Sina Blog, Sina Podcast, Netease News, Liujianfang, 56.com, Discuz!, Shuimu Community, Douban, YUPOO, Domestic, Xunlei Online, etc. use Nginx as Web Server or reverse proxy server.
The core features of Nginx
(1) Cross-platform: Nginx can be compiled and run on most Unix like OS, and there is also a ported version of Windows;
(2) The configuration is very simple: very easy to use. The configuration style is the same as that of program development, which is a god-like configuration;
(3) Non-blocking, high-concurrency connection: When data is replicated, the first stage of disk I/O is non-blocking. The official test can support 50,000 concurrent connections, and the number of concurrent connections ran to 20,000 to 30,000 in the actual production environment. (This is due to the use of the latest epoll model by Nginx);
(4) Event-driven: The communication mechanism adopts the epoll model to support larger concurrent connections.
(5) Master/Worker structure: A master process generates one or more worker processes.

(6) Small memory consumption: The memory consumption for processing large concurrent requests is very small. With 30,000 concurrent connections, only 10 Nginx processes that are started consume 150M of memory (15M*10=150M).
(7) Built-in health check function: If a certain web server on the back end of the Nginx proxy goes down, it will not affect the front end access.
(8) Bandwidth saving: GZIP compression is supported, and the Header header of the browser's local cache can be added.
(9) High stability: Used for reverse proxy, the probability of downtime is minimal.

Nginx configures static resources and cross-domain

Use nginx to be a static server. You can use nginx's reverse proxy to handle cross-domain

How to modify the configuration file:

  1. Find the directory where nginx is installed: nginx-1.8.1\conf\nginx.conf, find the configuration file nginx.conf, you can modify and save it directly, and you can just reload the service to nginx -s reload
  2. In cmd or git console cd, enter the nginx installation directory and enter conf,
    vim nginx.conf
    click i on the screen to enter the editing state, modify the relevant configuration
    After the modification, click Esc, and enter: wq to save and exit
    The modification takes effect, and the service nginx -s reload is reloaded

server {

Listening port number

listen 8181; # The name of the server server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location/{ Copy code

Static resource directory

root D:/ruanmou/gitWork/ruanmouLearn/webpack/jqueryProjects/build/; index index.html index.htm; # Add no-cache to the request at the end of html; if ($request_filename ~ .*\.(htm|html)$) { add_header Cache-Control no-cache; } #Picture cache time setting if ($request_filename ~ .*\.(png|jpg)$) { # add_header Cache-Control no-cache; add_header Cache-Control no-cache; } } location/api { Copy code

Set the protocol and address of the proxy server

proxy_pass https://www.17npw.net; index index.html yanshi.html; } location/book { Copy code

Set the protocol and address of the proxy server

proxy_pass http://localhost:3000; index index.html yanshi.html; add_header Cache-Control max-age=3601; } #error_page 404/404.html; # redirect server error pages to the static page/50x.html error_page 500 502 503 504/50x.html; location =/50x.html { root html; } Copy code


Which mainly relies on proxy_pass to forward the/api/x interface under localhost to https://www.17npw.net. This process is roughly as follows.

Common misunderstandings

  1. Useless ACA-Header?
    Many nginx cross-domain settings on the Internet have added content related to cross-domain header settings, such as
    add_header'Access-Control-Allow-Credentials' true ;
    add_header ' Access-Control-Allow-Headers''X-Requested-With';
    think about the above principle, do you think this is useful? The header of the ACA (Access-Control-Allow-) series is configured for cross-domain negotiation in cors, and it is unnecessary to configure this here.
  2. Does the proxy_pass domain name carry the'slash/'?
    Similarly, I saw some netizens on the Internet that when configuring proxy_pass, they would add a slash at the end, as follows, and then said that an error was reported, and the interface could not be found.

Location/api {
#proxy_pass b.test.com ;
proxy_pass https://b.test.com/;
Seeing this, let s think about it. The role of proxy_pass is to catch and send, adding a slash means All/api requests will be forwarded to the root directory, which means that/api will be replaced by/. At this time, the interface path will change, and/api will be missing. What about when the slash is not added? This means that the/api path will not be lost under the domain name forwarded to b.test.com.
In view of this situation, if the back-end interface has a uniform prefix, such as/api, then you should not configure the slash here. In another case, the back-end interface shit does not have a unified prefix, and it is necessary to distinguish it. Then add a unified prefix to all the front-end interfaces, such as/api, and then replace it by adding a slash~

Reference: www.2cto.com/os/201212/1...
Configure Cache-Control
HTTP protocol Cache-Control under Nginx to specify the caching mechanism followed by requests and responses.
Setting Cache-Control in the request message or response message does not affect the cache processing process in another message processing process.
The cache instructions at request include no-cache, no-store, max-age, max-stale, min-fresh, only-if-cached, etc.
The instructions in the response message include public, private, no-cache, no-store, no-transform, must-revalidate, proxy-revalidate, and max-age.

When the cache policy is met, the server will not send new resources, but it does not mean that there is no conversation between the client and the server, and the client will still send a request to the server.
In addition to using Cache-Control in the response, it can also be used in the request. We use the developer tool to simulate the request with Cache-Control: check Disable cache, refresh the page, you can see that there is a field Cache-Control: no-cache in the Request Headers.

At the same time, the Cache-Control field can also be found in Response Headers. Its value is must-revalidate, which is set by
the server. When Cache-Control is used in the request, its optional values are:

Use Cache-Control in the response The optional values are:

No-store has the highest priority.
In Cache-Control, these values can be freely combined. If multiple values conflict, they also have priority, and no-store has the highest priority. We can test it: do the following configuration in nginx:
server {
listen 88;
index index.php index.html index.htm index.nginx-debian.html;
location ~* ^.+.(css |js|txt|xml|swf|wav)$ {
add_header Cache-Control no-store;
add_header Cache-Control max-age=3600;
add_header Cache-Control public;
add_header Cache-Control only-if-cached;
add_header Cache- Control no-cache;
add_header Cache-Control must-revalidate;
Add a file type.css under/opt/ms, the content is as follows:
a{ color: #000000;}
a:focus,a:hover {text-decoration: none; color: #708090; }After
configuration, reload nginx and visit the address in the browser/type.css, you can see that the response header contains the fields in the nginx configuration:

repeat the refresh access, you will find that the status code is 200 each time, because the priority of no-store is the highest, and it is not saved locally, every time The server is required to send resources.

The choice between public and private
If you use CDN, you need to pay attention to this value. CDN vendors generally require the value of cache-control to be public to increase the cache hit rate. If your cache hit rate is very low and the amount of visits is large, you can see if you have set private and no-cache values. If you define max-age, you don't need to define public anymore, they have the same meaning.

You will see an etag field in the response header. This is because nginx is enabled by default. If you want to disable it, you can add a configuration etag off. This etag is the cache verification field we will look at next.

Cache verification
In the cache, we need a mechanism to verify that the cache is valid. For example, if the server's resources are updated, the client needs to refresh the cache in time; or the client's resources have expired, but the resources on the server are still old, and there is no need to resend them. Cache verification is used to solve these problems. In http 1.1, we mainly focus on the two fields Last-Modified and etag.

So is there a way to let the server know that the current cached files in the client are in fact the same as all of their own files, and then directly tell the client to say, "You can just use the cached files for this thing, and I haven't updated it here. After that, I won t pass it once again."

For example: C: Xiaofu, how old are you? S: Xiaoke, I am 18 years old.

C: Xiaofu, how old are you? I guess you are 18 years old. S: Damn, you know you still ask me? (304)

C: Xiaofu, how old are you? I guess you are 18 years old.
S: Xiaoke, I am 19 years old. (200)

In order to verify whether the cache file is updated between the client and the server, and to improve the reuse rate of the cache, Http1.1 adds several new header fields to do this.

When the Last-Modified (HTTP 1.1 product)
server returns a resource, it will return the last modification time of the resource to the client through the Last-Modified field. The client brings Last-Modified through If-Modified-Since or If-Unmodified-Since the next time it requests, the server checks whether the time is consistent with the last modification time of the server: if it is the same, it returns a 304 status code and does not return resources ; If they are inconsistent, return 200 and the modified resource, and bring the new time.

The difference between If-Modified-Since and If-Unmodified-Since is:
If-Modified-Since: Tell the server if the time is consistent, return status code 304
If-Unmodified-Since: Tell the server if the time is inconsistent, return status code 412
How Nginx Enable ETag to improve access speed

The full name of ETag is EntityTags. In the HTTP protocol specification, "ETag" is defined as "the entity value of the requested variable". We can also understand ETag as a token associated with a client and a server. This mark tells the client whether the current web page has changed since the last request. When there is a change, the value of ETag is recalculated and a 200 status code is returned. If there is no change, a 304 status code is returned. This will not reload the entire page information.
etag turns on
etag off/on by default ;

It is still flawed to judge purely by the modification time. For example, the last modification time of the file has changed, but the content has not changed. For such a situation, we can use etag to handle it.
The etag method is as follows: the server calculates the resource through an algorithm, obtains a string of values (similar to the md5 value of a file), and then returns the value to the client through etag, and the client passes If-None in the next request -Match or If-Match with this value, the server will compare and verify the value: if they are the same, do not return the resource.
The difference between If-None-Match and If-Match is:
If-None-Match: Tell the server if they are consistent, return status code 304, if they are inconsistent, return the resource
If-Match: Tell the server if they are inconsistent, return status code 412
browser on The 3 attributes of
Cache : Cache-Control:
Set the relative expiration time, max-age indicates the cache time in seconds. If you only cache static resources once, you can set the value of max-age to 315360000000 (ten thousand years).
Expires : (HTTP 1.0 product)
Set the absolute expiration time in minutes, the priority is lower than Cache-Control, and set Expires and Cache-Control at the same time, the latter will take effect.
Note: The
Last-Modified attribute is usually the same as Expires or Cache-Control attributes Used in conjunction, because even if the browser is set to cache, when the user clicks the "Refresh" button, the browser will ignore the cache and continue to send requests to the server, then Last-Modified will be able to reduce response costs well.

ETag will return a resource ID to the browser, if there is a new version, send it normally and attach the new ID, otherwise it will return 304, but in the case of server clusters, each server will return a different ID, so it is not recommended to use ETag.

Before introducing Cache-Control, let's talk about two things that are easy to overlook:


  1. The cache switches are: pragma, cache-control.
  2. Cache verification includes: Expires, Last-Modified, etag.

In the http1.0 era, setting the caching method for the client can be regulated by two fields-Pragma and Expires. Although these two fields can be discarded long ago, in order to make the http protocol backward compatible, you can still see that many websites still carry these two fields.

"Expires time is relative to the server and cannot be guaranteed to be consistent with the client time." http1.1 adds Cache-Control to define the cache expiration time. Note: If Expires and Cache-Control appear in the message at the same time, the Cache-Control shall prevail.
In other words, the priority from high to low is Pragma -> Cache-Control -> Expires.

  1. From the point of view of status codes, their relationship is as follows:

    Based on nginx configuration and usage summary
    Distributed system, it is best to use Last-Modified and Expires to turn off Etag.
  1. Close etag
    http {

    etag off;
    } #Use
    Last-Modified and Expires
    (2) Configure last-modified (enabled by default) and expires

location ~. .(gif|jpg|jpeg|png|bmp|swf)$
expires 30d;
location ~.
expires 12h;
For those configured with multiple locations(upstream), Yes:
autoindex on;
if (KaTeX parse error: Can't use function'\.' in math mode at position 25: ilename ~* ^.*?/. (Txt|doc|pdf|ra ){
add_header Content-Disposition:'attachment;';
if (KaTeX parse error: Can't use function'\.' in math mode at position 25: ilename ~* ^ .*?/. (Gif|jpg|jpeg|p ){
expires 30d;
if (KaTeX parse error: Can't use function'\.' in math mode at position 25: ilename ~* ^. *?/. (Js|css)){
expires 12h;
Nginx configuration performance optimization

Nginx service Rewrite and Proxy_Pass

Reference link: