Nginx is known to be a good alternative to Apache services. Nginx is characterized by small memory and strong concurrency capability. In fact, Nginx’s concurrency capability performs better in the same type of web servers. Therefore, famous domestic manufacturers such as Taobao, JD, Baidu, Sina, netease, Tencent and so on are all using Nginx website.

Nginx profile

Nginx is an open source, high-performance, and reliable Web and reverse proxy server that supports hot deployment. It also provides IMAP/POP3/SMTP services that can run continuously and provide hot updates. Nginx has a low memory footprint, high concurrency, and, most importantly, is free and commercially available, making it easy to configure and use.

Nginx characteristics
  • High concurrency and high performance

  • The modular architecture makes it very scalable

  • Asynchronous non-blocking event-driven model similar to Node.js

  • Run without restart

  • Hot deployment and smooth upgrade

  • Completely open source, good ecology

The most important use scenarios for Nginx are:
  • Static resource service

  • Reverse proxy services, including caching and load balancing

  • API service, OpenResty

Therefore, today the migrant worker brother will give you a common configuration list of Nginx, for you to learn and production configuration reference. It mainly includes the following three aspects:

  • Basic configuration

  • Advanced configuration

  • Security configuration

Basic configuration

Remove unused Nginx modules

./configure --without-module1 --without-module2 --without-module3 /configure --withouthttp_spdy_module --withouthttp_spdy_module --withouthttp_spdy_module --withouthttp_spdy_module Make sure the module you disable does not contain the instructions you need to use! Before deciding to disable a module, you should check the Nginx documentation for the list of directives available for each module.Copy the code

Smooth upgrade and rollback of Nginx

Smooth upgrade and rollback of Nginx in 1 minute

Configure processes

worker_processes 8; #Nginx Number of processes, recommended by the number of cpus, usually a multiple of this (for example,2 quad-core cpus count as 8). worker_rlimit_nofile 65535; # Maximum number of file descriptors that can be opened by an Nginx process # Maximum number of connections allowed per processCopy the code

Listen on port

server { listen 80; Server_name www.mingongge.com; # location / {root/WWW/WWW; Index index.html index.htm; # Default home type deny 192.168.2.11; All allow 192.168.3.44; * all * all * all * all * allCopy the code

Tip: domain name matching four ways to write

Exact match: server_name www.mingongge.com; Server_name *.mingongge.com; Server_name www.mingongge.*; Server_name ~^ WWW \.mingongge\.*$; Matching priority: Exact match > Left wildcard match > Right wildcard match > Regular expression matchCopy the code

Configure the Nginx status page

/ root @ proxy ~ # cat/usr/local/nginx/conf/nginx. Conf... ... location /NginxStatus { stub_status on; access_log on; auth_basic "NginxStatus"; auth_basic_user_file conf/htpasswd; }... ... [root@proxy ~]# /usr/local/nginx/sbin/nginx -s reloadCopy the code

Nginx Log (Access and error log management)

error_log /var/log/nginx/error.log warn; Events {worker_connections 1024; }http {.................. log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; # configuration log mode access_log/var/log/nginx/access. Log the main; Configure access log storage directoryCopy the code

The above configuration is only the basic configuration of Nginx’s own log. In the actual production environment, we need to collect and analyze logs to better locate problems. It is recommended that you: super dry goods! Collect NGINX logs using fileBeat, Logstash, and rsyslog

HTTP configuration

HTTP {sendfile on # keepalive_timeout 65 # timeout for client server requests}Copy the code

Static Resource Configuration

server {  listen 80;  server_name mingongge.com;  location /static {        root /wwww/web/web_static_site;   }}
Copy the code

You can also use the following method

location /image { alias /web/nginx/static/image/; } Note: You must add/at the end of alias, and it can only be in locationCopy the code

The reverse proxy

For example, if the production environment (in the same service) has different projects, it is more practical to use the reverse proxy to do the request forwarding.

http {............. Upstream product_server {127.0.0.1:8081; } upstream admin_server {127.0.0.1:8082; } upstream test_server {127.0.0.1:8083; / {proxy_pass http://product_server; } location /product/{ proxy_pass http://product_server; } location /admin/ { proxy_pass http://admin_server; } location /test/ { proxy_pass http://test_server; }}}Copy the code

More on Nginx practice: Location path matching

Load balancing

Upstream server_pools {server 192.168.1.11:8880 weight=5; Server 192.168.1.12:9990 weight = 1; Server 192.168.1.13:8989 weight = 6; }server {listen 80;}server {listen 80; server_name mingongge.com; location / { proxy_pass http://server_pools; }}Copy the code

Other configuration related to the agent

proxy_connect_timeout 90; Proxy_send_timeout 90; Proxy_read_timeout 90; Proxy_buffer_size 4k; # nginx buffers proxy_buffers 4 32k; #proxy_buffers buffer proxy_busy_buffers_size 64K; # buffer size (proxy_buffers*2) Proxy_set_header Host $Host; proxy_set_header X-Forwarder-For $remote_addr; Get the real IP address of the clientCopy the code

Advanced configuration

Redirection configuration

location / { return 404; }location / {return 404 "pages not found"; }location / {return 302 /blog; # to return a status code + redirect the location/address} {return https://www.mingongge.com; # return redirection addressCopy the code

The sample is as follows

server { listen 80; server_name www.mingongge.com; return 301 http://mingongge.com$request_uri; }server {listen 80; server_name www.mingongge.com; location /cn-url { return 301 http://mingongge.com.cn; }} server{ listen 80; server_name mingongge.com; To configure root HTML in the local hosts file; location /search { rewrite ^/(.*) https://www.mingongge.com redirect; } location /images { rewrite /images/(.*) /pics/$1; } location /pics { rewrite /pics/(.*) /photos/$1; } location /photos { }}Copy the code

Set the upper limit of the buffer capacity

This setting prevents buffer overflow attacks (also on the Server module)

client_body_buffer_size 1k; client_header_buffer_size 1k; client_max_body_size 1k; large_client_header_buffers 2 1k; No number of HTTP requests will overflow the server's bufferCopy the code

Limit the maximum number of connections

In the HTTP module and outside the server module, configure limit_conn_zone to set the IP address for connection. In the HTTP, server, or Location module, configure limit_conn to set the maximum number of IP connections.

limit_conn_zone $binary_remote_addr zone=addr:5m; limit_conn addr 1;Copy the code

Gzip compression

Gzip_types # Compressed file type: text/plain Text/CSS application/ JSON application/ X-javascript text/ XML application/ XML application/xml+rss text/javascriptgzip on; Gzip_disable "msie6"# disable gzip function gzip_static for the specified client; Gzip_proxied any; gzip_proxied any; # Allow/disable compression of response streams based on request and response gzip_min_length 1000; # set the minimum number of bytes to enable compression for data gzip_comp_level 6; # Set compression level of dataCopy the code

Cache configuration

Open_file_cache_valid # Specifies the interval for detecting correct information in open_file_cache. Open_file_cache_min_uses specifies the interval for detecting correct information in open_file_cache Open_file_cache_errors specifies whether the error information location ~ is cached when searching for a file . * \. (GIF | JPG | jpeg | PNG | BMP | SWF) type of a cache file $# {expires 3650 d; # specify cache time} the location ~. * \. (js) | CSS? $ { expires 3d; }Copy the code

Configure the SSL certificate and skip HTTPS

Server {listen 192.168.1.250:443 SSL; server_tokens off; server_name mingonggex.com www.mingonggex.com; root /var/www/mingonggex.com/public_html; ssl_certificate /etc/nginx/sites-enabled/certs/mingongge.crt; ssl_certificate_key /etc/nginx/sites-enabled/certs/mingongge.key; Ssl_protocols TLSv1 TLSv1.1 TLSv1.2; }# Permanent Redirect for HTTP to HTTPSserver { listen 80; server_name mingongge.com; https://$server_name$request_uri; }Copy the code

Traffic Mirroring

location / { mirror /mirror; proxy_pass http://backend; }location = /mirror { internal; proxy_pass http://test_backend$request_uri; }Copy the code

Current limiting function

Traffic limiting is configured with two main directives, limit_req_zone and limit_req

limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s; server { location /login/ { limit_req zone=mylimit; proxy_pass http://my_upstream; }}Copy the code

More, more detailed flow limiting configuration please refer to: Sunflower Bible! This article deals with Nginx traffic limiting configuration

Common Nginx built-in variables

Security configuration

Disable server_tokens item

Server_tokens causes the 404 page to display the current version of Nginx if opened. This is obviously not secure, as hackers will use this information to try out the vulnerability in the appropriate version of Nginx. If server_tokens off is set in the nginx.conf HTTP module, for example:

Server {listen 192.168.1.250:80; Server_tokens off; server_name mingongge.com www.mingongge.com; access_log /var/www/logs/mingongge.access.log; error_log /var/www/logs/mingonggex.error.log error; root /var/www/mingongge.com/public_html; index index.html index.htm; }# Restart Nginx:Copy the code

Disable illegal HTTP User Agents

User Agent is an identifier of the browser in THE HTTP protocol. Prohibiting illegal User Agent can prevent some requests from crawlers and scanners and prevent these requests from consuming a large amount of Nginx server resources.

In order to better maintenance, best to create a file, containing don’t expect the user agent list for example/etc/nginx/blockuseragents rules include the following:

map $http_user_agent $blockedagent { default 0; ~*malicious 1; ~*bot 1; ~*backdoor 1; ~*crawler 1; ~*bandit 1; }Copy the code

Then put the following statement into the server module of the configuration file

include /etc/nginx/blockuseragents.rules; Add an if statement to set the page to be blocked:Copy the code

Block pictures outside the chain

Location /img/ {valid_referers none blocked 192.168.1.250; if ($invalid_referer) { return 403; }}Copy the code

Block malicious access

Pretty good! Nginx is used to block malicious access

Ban unwanted HTTP methods

Some Web sites and applications can support only GET, POST, and HEAD methods. Add the following methods to the serve R module in the configuration file to prevent spoofing attacks

if ($request_method ! ~ ^(GET|HEAD|POST)$) { return 444; }Copy the code

Disable SSL and enable only TLS

Avoid using SSL and use TLS instead. The following configurations can be placed in the Server module

Ssl_protocols TLSv1 TLSv1.1 TLSv1.2;Copy the code

With this set of configurations in place, your Nginx server should be sufficient for your actual production needs.

You are also welcome to leave positive comments to add to this common configuration list, so that it is more complete, more complete.