website development hsn code



1.1 Purpose

In order to better guide the deployment and testing art promotion systemnginxWebsite server high performance at the same time, safe and stable operation at the same time,Need to be rightnginxService tuning and reinforcement;

This timeNginxService adjustment reinforcement is mainly from the following parts:

  • Module performance optimization
  • System kernel optimization
  • Compiled and installed optimization
  • Performance parameter optimization
  • Safety reinforcement configuration

1.2 Scope

This document is for internal use,Prohibit,Help R & D personnel,Operating and maintenance personnel provide technical document reference for the long -term stable operation of the system。

1.3 Reader

  1. project manager
  2. Developer
  3. Testers
  4. Operation and maintenance personnel
  5. Relevant leader

2.Reference description#

2.1 Help for reference

NginxIt is a high -performanceHTTPAnd reverse proxy server,It's also aIMAP/POP3/SMTPserver。NginxAs a load balancing server, Nginx Can be supported directly inside Rails and PHP Procedure to serve outside,Can also support as HTTPAgent server service outside the outside world。

(website development hsn code)NginxVersion selection:

  • Mainline version The latest version of,Recommended test business items
  • Stable version Stable version,Recommended projects are online actual use
  • Legacy versions historic version,Not recommended to choose a fragile vulnerability

(website development hsn code)Project structure:

#CompilenginxProject structure
├── client_body_temp  #Temporary file storage directory on the client
├── conf              #nginxConfiguration file storage directory
├── fastcgi_temp      #fastcgiTemporary file storage directory
├── html              #Stop static resources or script files
├── logs              #nginxLog file
├── proxy_temp        #nginxPositive/Reverse proxy cache file storage directory
├── sbin              #nginxexecutable file
├── scgi_temp         #scgiTemporary file directory
└── uwsgi_temp        #uwsgiTemporary file storage directory

NginxDocument help:
NginxHome address directory: /usr/share/nginx/html
NginxConfiguration file:

  • /etc/nginx/nginx.conf
  • /usr/local/nginx/conf/nginx.conf
  • /usr/local/etc/nginx/nginx.conf

2.2 Parameter Description

(website development hsn code)localtion RequesturlIt is really a regular expression:

# Grammatical rules: 
location [=|~|~*|^~] /uri/ { ... }

# Parameter analysis: 
= Express accurate matching,This priority is also the highest
/ Universal matching,Any request will match,Default matching.
~ Express the regular match that distinguishes the case
~* Express the regular match that does not distinguish between lower and lowercase(The only difference from the above is the case) !~and!~*They are the regular forms that are not matched and uninterrupted.
!~,!~* : The identification is the regular as a regular manuscript that does not match and does not match the case.
^~ express uri Start with a conventional string,Understand as matching url Path。nginx wrong url Coding,So the request is/static/20%/aa,Can be ruled^~ /static/ /aa Match(Pay attention to space)

Nginx Matching judgment expression:

-f and !-f: Used to determine whether there are files
-d and !-d: Used to determine whether there is a directory
-e and !-e: Used to determine whether there are files or directory
-x and !-x: Used to determine whether the file can be executed

E.g,The last end of the match is the static of the below suffix and determine whether the file exists, If there is no existence404。

(website development hsn code)location ~* \.(js|css|jpg|jpeg|gif|png|swf)$ {
  if (-f $request_filename) { 
    return 403;

3.3 Module description

(website development hsn code)View the useful module compile parameter:

#Can run by running "./configure --help" View compilation help,Determine whether you need to install which modules,Such as the followingssiModule can realize accessshtmlpage
./configure -help

(website development hsn code)

OpengzipCompression output(Often greater than1kbStatic file),Reduce network transmission;

gzip_min_length 1k #Set the minimum byte byte byte byte by byte that allows compressed pagecontent-lengthGet in,The default value is20
gzip_buffers 4 16k #Set up the system to obtain the cache of several units for storagegzipData stream of compression results。4 16kRepresent16kUnit,Install the original data size16kUnit4Double application memory。
gzip_comp_level 2 #gzipCompression ratio,Value from1arrive9The larger the number, the higher the compression rate,More consumingCPUThe higher the load
gzip_types #matchmimeType compress,Whether or not you specify”text/html”Type will always be compressed,Recommended configuration:`gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript。`
gzip_http_version 1.0 #For identification http The early browser of the protocol does not support the early browser Gzip compression,Users will see garbled code,So in order to support the previous version, this option is added;If you use it Nginx The reverse proxy and expectation are also enabled Gzip Compressed,Since the end communication is http/1.0,So please set it to 1.0。
gzip_proxied any #NginxWhen you are reverse proxy, use it,Decided whether the result returned by opening or closing the back server is compressed,The premise of matching is that the back -end server must be returned to include”Via”of headerhead。
gzip_vary on #andhttpThe relationship between the head will add one to the response header Vary: Accept-Encoding ,Can make the front -end cache server cache passgzipCompressed page,Such asSquidCache passNginxCompressed data。

nginxCan be used to request routingFastCGIThe server runs the application from various frameworks andPHPProgramming language, etc.。Can openFastCGIThe cache function and the static resources are peeled off,So as to improve performance。

(website development hsn code)instruction:fastcgi_temp_path  #definitionFastCGICache file preservation temporary path。
instruction:fastcgi_cache_path  #definitionFastCGIThe cache file preservation path and other parameters of the cache。Cache data is stored in the form of binary data files,Cache file name andkeyThey are all accessedURLuseMD5Calculated results。Save the cache file firstfastcgi_temp_pathIn the specified temporary directory,Then move tofastcgi_cache_pathSpecify the cache directory。Suggestfastcgi_temp_pathandfastcgi_cache_pathSet to the same partition,Move operations at the same partition is higher efficiency。Exemplary:
fastcgi_temp_path /tmp/fastcgi_temp;
fastcgi_cache_path /tmp/fastcgi_cache levels=1:2 keys_zone=cache_fastcgi:16m inactive=30m max_size=1g;
# levelsSpecify the directory structure,Subtraction number16Base;
# keys_zoneSpecify the name and size of the shared memory area,Used to save cachekeyAnd data information;
# inactiveSpecify the time for caching data to save,If you are not accessed during this time, you will be removed;
# max_sizeSpecify the maximum disk space used by cache,When the capacity is exceeded, the recent data will be deleted at least。
#Use in examples/tmp/fastcgi_tempBeFastCGICache temporary directory;/tmp/fastcgi_cacheBeFastCGIThe final directory of cache preservation;The first -level sub -directory is16One prescription16indivual,The secondary subdirectory is16of2Secondary256indivual;The shared memory area is namedcache_fastcgi,used internal memory128MB;The cache expires time is30minute;The maximum space of the cache data is stored in the disk1GB。

instruction:fastcgi_cache_key        # definitionFastCGICache keyword。Open upFastCGICaches must be added with this configuration,Otherwise, visit everythingPHPThe requests are the first to accessPHPdocumentURLthe result of。
instruction:fastcgi_cache_valid      # SpecifiedHttpStatus code specify cache time。
instruction:fastcgi_cache_min_uses   # How many requests are specified?URLWill be cached。
instruction:fastcgi_cache_use_stale  # Specify the connectionFastCGIWhen the server is wrong,What are the cases of expired data response。
instruction:fastcgi_cache            # Which shared memory area is used for cache

(website development hsn code)

Long connection has a great impact on performance,ReduceCPUTo open or close the connection with network overhead;

  • keepalive_timeout The time when the idle long connection keeps open;
  • keepalive_requests The number of requests that can be requested by a single client length connection;
  • keepalive Related instructions for upstream server long connection,Each work process is a large number of connections to the upstream server to keep the number of connections.(No default)。
    To use a long connection connected to the upstream server,The instructions below must be configured in the file:
    proxy_http_version 1.1;
    proxy_set_header Connection "";

NginxOpen supportHttpsProtocolSSLModule

#Nginx SSLPerformance tuning
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
#Pay attention to the encryption here
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

3.Service optimization#

3.1 System core

LinuxThe default value of the kernel parameter is not suitable for high concurrency,LinuxKernel tuning,It mainly involves network and file system、Memory optimization,

  • Temporary methods can be adjusted by adjustment/ProcFile system,Pay attention to adjustment/ProcAfter the file system is restarted, restore to the default value(Not recommended)。
  • Permanent modification/etc/sysctl.confConfigure file permanent preservation

The following is my commonly used kernel tuning configuration:

grep -q "net.ipv4.tcp_max_tw_buckets" /etc/sysctl.conf || cat >> /etc/sysctl.conf << EOF
net.core.rmem_default = 262144
net.core.rmem_max = 16777216
net.core.wmem_default = 262144
net.core.wmem_max = 16777216

#Cushion queue settings are related to connection and how they queue up#
#The adjustment system initiated at the same timetcpNumber of connections,In high concurrency requests,The default value may cause the link time or re -transmission,Therefore, the number of concurrent requests is needed to adjust this value。
#net.core.somaxconn = 262144
#SubmitCPUThe rate of data packet buffer in the front network card,Increasing this value at high bandwidth can improve performance;Check the error of this settings in the kernel log file,Modify this value according to the recommendations in the network card documentation。
net.core.netdev_max_backlog = 262144
#How many sets are there in the setting systemTCPThe socket is not associated to any user file handle
net.ipv4.tcp_max_orphans = 262144
#Used to record the maximum value of the connection request that has not received the client confirmation information(Change according to the class)
net.ipv4.tcp_max_syn_backlog = 1024

#set uptimewaitThe number is default180000Set10000。
net.ipv4.tcp_max_tw_buckets = 10000

#The start and end of the high concurrency end value range The general port number setting is1024arrive65000,It is used to set the port range that allows the system to open;
net.ipv4.ip_local_port_range = 1024 65500

#Used to set uptimewaitQuickly recycle
net.ipv4.tcp_tw_recycle = 1

#Used to set up reuse,AllowTIME-WAIT socketsRe -used for newTCPconnect。
net.ipv4.tcp_tw_reuse = 1

#Used to set upSYN Cookies,AppearSYNWhen the queue overflows,Open upcookiesProcessed。
net.ipv4.tcp_syncookies = 1

#Determined the kernel before giving up the connection and sendingSYN+ACKQuantity。
net.ipv4.tcp_synack_retries = 1
#Means sending it before the kernel abandon the establishment of the connectionSYNQuantity。
net.ipv4.tcp_syn_retries = 1
#Decided that the socket is kept inFIN-WAIT-2State。The default value is60Second。
#It's important to set this value correctly,Sometimes even if a load is smallWebserver,There will also be a large number of dead words and the risk of memory overflow。
net.ipv4.tcp_fin_timeout = 30
#Options representkeepaliveWhen enabled,TCPsendkeepaliveThe frequency of message。The default value is2(The unit is hours)。
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 3
net.ipv4.tcp_mem = 786432 1048576 1572864

#File descriptive restrictions of system level#
kernel.sem = 250 32000 100 128
fs.file-max = 6815744
vm.swappiness = 10
fs.aio-max-nr = 1048576
sysctl -p

File descriptive symbol
The file descriptor is the operating system resources,Used to represent connection、Open file,And other information。NGINX Each connection can use two file descriptors。
For exampleNGINXWhen acting as an agent,Usually a file descriptor represents the client connection,Another connection to the proxy server,If it is turned onHTTP Keep connection,This ratio will be lower(Translate:Why is it lower?)。

For systems with a large number of connection services,The following settings may need to be adjusted:

#Modify the descriptor method of the file
vim /etc/security/limits.conf
* - nofile 65536  #User -level file descriptor limit

#Then perform the start -up file modification
echo "ulimit -Hsn 65536" >> /etc/profile

3.2 Compile and optimization

(website development hsn code)Streamlined module:NginxDue to the continuous addition of new features,More and more modules are attached,It is recommended that the general commonly used server software uses source code compilation and installation management;

(1) DecreaseNginxCompiled file size

  • CompileNginxBy defaultdebugPattern,IndebugA lot of tracking will be inserted in the patternASSERTInformation,After the compilation is completedNginxThere are several megs;So you can compile before compiling,Modify the relevant source code,Canceldebugmodel;
# Find the source code directory auto/cc/gcc  document debug
CFLAGS="$CFLAGS -g" #Note or delete these two lines,Can be canceleddebugmodel。

ls -alh /usr/local/nginx/sbin/nginx
-rwxr-xr-x. 1 root root 915K Aug 17 09:49 /usr/local/nginx/sbin/nginx  #You can see that the volume is greatly reduced

(2) SpecifyGCCCompile parameter
ReviseGCCCompilation parameters to improve compilation and optimization level Steady. -O2 This is also the optimization level recommended by most software compilation。

  • NginxSource code file auto/cc/gcc search NGX_GCC_OPTdefaultGCCThe compile parameter is-O,Can directly modify the content as NGX_GCC_OPT="-O2" Maybe ./configureAdd during configuration--with-cc-opt='-O2'Option。
--with-cc-opt='-O3'  #Compile level
--with-cpu-opt=CPU   #Specific CPU Compile,Effective value includes:pentium, pentiumpro, pentium3, # pentium4, athlon, opteron, amd64, sparc32, sparc64, ppc64
website development hsn code

(website development hsn code)

GCCCompile parameter optimization [Option] A total5Level compilation optimization level:

  • -O0:No optimization。
  • -Oand-O1:Use that can reduce the size of the target code and the execution time and will not make the compilation time significantly increase,When compiling large programs, it will significantly increase the use of memory during compilation。
  • -O2:Include-O1Optimization and increased the compromise of the target file size and execution speed。The compiler does not execute the cycle development and the internal connection of the function。This option will increase the execution performance of the compilation time and target file。
  • -Os:Can be regarded as -O2.5,Specialized optimizing the target file size,Execute all the size of the target file-O2Optimization option,And implement the optimization option to reduce the size of the target file。Applicable to use when disk space is tight。But there may be unknown problems,Moreover,Common procedures are unnecessary to use。
  • -O3:Open everything -O2 Optimization options increase -finline-functions、-funswitch-loops、-fgcse-after-reload Optimization option。Relative to -O2 Performance has not improved more,Compile time is also the longest,The generated target files are also larger and more memory.,Sometimes performance does not increase but decreases,Even an unpredictable problem(Include errors),So it is not recommended by most software installation,This optimization level can be used unless there is absolute grasp。

Common compilation parameters:

#Compile0:Conventional compilation parameters
configure arguments: 
#Installed directory or path#
#Execute the corresponding modulenginxTemporary files reserved#
#Started users and group users#
#Module parameter#
#The additional parameters will be added toCFLAGS#
--with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' 
#Set the attachment parameters,Link system library#
-with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'

#Compile1:Excess module
./configure \
"--prefix=/App/nginx" \ 
"--user=nginx" \ 
"--group=nginx" \
"--with-http_stub_status_module" \
"--without-http_auth_basic_module" \
"--without-http_autoindex_module" \
"--without-http_browser_module" \
"--without-http_empty_gif_module" \
"--without-http_geo_module" \
"--without-http_limit_conn_module" \
"--without-http_limit_req_module" \
"--without-http_map_module" \
"--without-http_memcached_module" \
"--without-http_proxy_module" \
"--without-http_referer_module" \
"--without-http_scgi_module" \
"--without-http_split_clients_module" \
"--without-http_ssi_module" \
"--without-http_upstream_ip_hash_module" \
"--without-http_upstream_keepalive_module" \
"--without-http_upstream_least_conn_module" \
"--without-http_userid_module" \
"--without-http_uwsgi_module" \
"--without-mail_imap_module" \
"--without-mail_pop3_module" \
"--without-mail_smtp_module" \
"--without-poll_module" \
"--without-select_module" \

(website development hsn code)

3.3 Performance optimization

Caches and compression and restrictions can improve performance
NGINXSome additional functions can be used to improveWebApplication performance,When tuningwebThe application does not need to be turned off, but it is worth mentioning,Because their impact may be important。

  • 1)Cache
    EnlightenNGINXCache scene,One groupwebOr apply server load balancing,It can significantly shorten the response time to the client,At the same time, greatly reduce the load of the back -end server。The cache itself can be used as a topic,Here we won't try to talk about it anymore。
# Web resource cache
location ~* \.(xml|html|htm)$ {
  # Resource Decision absolute directory settings
  root /var/www/html;
  # The relative path or complete path of the log file
  access_log /path/to/file.log;
  # Open log record
  access_log on;
  # Set the expiration time
  expires 24h;

# style、JS、Picture resource cache
location ~* \.(css|js|ico|gif|jpg|jpeg|png)$ {
  root /var/www/html/res;
  # Disable404Error log
  log_not_found off;
  # Closure log
  access_log off;
  # Cache time7sky
  expires 7d;

# Font resource cache
location ~* \.(eot|ttf|otf|woff|woff2|svg)$ {
  root /var/www/html/static;
  log_not_found off;
  access_log off;
  expires max;
  • 2)compression
    So using smaller network bandwidth。However, although compression data will consumeCPUresource,But it is very effective to do this when the network bandwidth is used。have to be aware of is,Can't compress the compressed file for examples such asJPEG document。
# Open up gzip compression
gzip on;
# Open upgzipThe minimum file of compression,Files smaller than setting value will not compress
gzip_min_length 2k;
# gzip Compression level,1-10,The larger the number, the better the better,The more occupiedCPUtime,There will be detailed instructions later
gzip_comp_level 2;
# Type of compressed file,javascriptThere are many shapes,The value can mime.types Find in the file。
gzip_types text/plain text/css text/javascript application/javascript application/x-javascript application/xml application/x-httpd-php image/x-icon image/jpeg image/gif image/png image/svg+xml image/avif image/webp font/ttf font/opentype;
# Proposehttp headerAddVary: Accept-Encodingsupport
gzip_vary on;
  • 3)limit
    Prevent users from spending too much resources,Avoid affecting system performance and user experience and security,Here are related instructions:
limit_conn and limit_conn_zone  # NGINXThe number of acceptance of customer connection,Such as a singleIPConnection of the address。Setting these instructions to prevent a single user from opening too much connection,Consume beyond your own resources。
limit_req and limit_req_zon #NGINXHandling the speed limit of request,andlimit_rateHave the same function。Can improve security,Especially for the login page,Set a reasonable value by setting a reasonable value for user restrictions,Avoid too slow programs to cover your application request(for exampleDDoSattack)。
limit_rate #  Restrictions on the response speed transmitted to the client(Every customer who opened multiple connections consumes more bandwidth)。Set this limit to prevent system overload,Make sure that all clients are more uniform service quality。
max_conns #The server instruction parameters in the upstream configuration block。A single server in the upstream server group can accept the maximum concurrent number。Use this restriction to prevent the upstream server from overloading。Set value to0(Defaults)Indicates that there is no restriction。
queue (NGINX Plus - Commercial version provided) # Create a queue,Used to store in the upstream server, the biggest to themmax_consRequest to limit quantity。This instruction can set the maximum value of the queue request,You can also choose to set up the maximum waiting time before the wrong return(The default value is60Second)。If you ignore this instruction,The request will not be placed in the queue。

Simple example:

http {
  # Please configure the same according to business needsIPAddress connection number
  limit_conn_zone $binary_remote_addr zone=www_weiyigeek_top:10m;
  # Please configure the same according to business needsIPAddress request rate
  limit_req_zone $binary_remote_addr zone=blog_weiyigeek_top:10m rate=1r/s;

  server {
    # It is recommended to create a black and white list
    allow internalIPOr load balancingIP;
    deny MaliciousIP;
    # Limiting
    location ^~ /download/ { 
      # Indicate a singleIPThe number of connections does not exceed 2 indivual
      limit_conn www_weiyigeek_top 2; 
      # Indicate a singleIPThe request rate is1sone, There are not many requests that are allowed to exceed the frequency limit5indivual,Most requests cannot be exceeded burst + rate quantity。
      limit_req zone=blog_weiyigeek_top burst=5 nodelay; 
      alias /data/;

  • 4)Reduce diskIO
    Reduce diskIOThe number can help us better improve the server performance,Enhance the load capacity of the server。
# Close does not need to record the specified directory or file access log
access_log off;
error_log /dev/null

# To create a cache zone for the log of the log, decreaseIOfrequency,For example, the cache is reached below128kOr the log refresh time is1mTime will be written into the log file(gzip Compression log-On -demand opening)
access_log /var/log/nginx/access.log main buffer=128k gzip flush=1m;

3.4 Operation optimization

1) Permanent redirection

(website development hsn code)If your site needs to be givenhttp URLredirect tohttps,It is not recommended to set up permanent redirect,Not a temporary redirection,This can help your site better included(SEO)。

(website development hsn code)E.g,Configuration http Towards https Jump (permanent)

# Way1.Redirect(Redirect)- recommend
server {
  listen 80;
  return 301 https://$host$request_uri;

# Way2.ReWrite Rewrite
server {
  listen 80;
  # Judgment requesthostwhether or not ,if The rewriting is 
  if ($http_host !~ "^www\.weiyigeek\.top#34; {
    rewrite ^(.*)$1 permanent;

3.5 Configuration optimization

nginxOptimization of the configuration file instruction



(website development hsn code)illustrate




The choice of work process includes(But not limited to)CPUCore quantity、The number of hard disks and load mode of storage data

set up auto or `cat /proc/cpuinfo



NginxThe default is not openedCPUBind,Binding work process to correspondingCPUcore

Multi -coreCPUSuggest settingsCPUBind,Binding sample:
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;



Open the number of files(Defaults1024),Limited to the number of user processes limited by the system opens the number of files,If the system is not set, use the default value of the system

(website development hsn code)Modify the number of users to open the file limit:
echo "* - nofile 65536" >> /etc/security/limits.conf
Modify allShellPass throughShellThe startup process opens the number of files:
echo "ulimit -n 65536" >> /etc/profile
Take effect(Effective after restarting): ulimit -n 65536



NginxThe maximum number of connections of a work process,Not only limited to client connection,Including other connections such as the back -end by the proxy server

Suggest settings worker_rlimit_nofile Equal

(website development hsn code)mian


(website development hsn code)existhttporserverorlocationIn the environmentsendfileinstruction。
NGINXNo need to switch to user mode,Just write the content on the cache or disk into the puttings and the speed is very fast,Less consumingCPUcycle。
Pay attention to usesendfile()Data copy can bypass the user's attitude but not applicable to conventionalNGINXProcess chain and filter that changes content, such asgzip

Suggest set on



(website development hsn code)Shock problem:
If the instruction value is on Open up,Then wake up a work process to receive and deal with a new connection,The rest of the work process continues to sleep
If the instruction value is off closure,Then it will awaken all work processes,Through the system passuseSpecified network instructionIOModel scheduling determine which work process is processed by which work process,The work process that does not receive the connection request continues to sleep

onOpen status for stable parameter values;
offClose status to improve performance and throughput, but it will bring more consequences of consumption of other resources such as context switching or rising loads, etc.(recommend)

(website development hsn code)main-events


DefinedNginxSet the rotation method for reusing the client thread(It can also be said to be a multi -road reuse networkIOModel),Naturally, it is a higher priority to choose higher efficiency(Just default)

use epoll



(website development hsn code)Open the closure and open the file cache default value off closure,It is strongly recommended to turn on the system overhead that can be reopened to save the response time brought by the same file

max=The maximum number of digital setting cache elements
inactive=Timeout timeout Use when the cache overflowsLRU(Most recently used)Algorithm delete the element in the cache;During this time, if the cache element is not accessed, it will be deleted from the cache;
open_file_cache max=65536 inactive=60s



Set up inspectionopen_file_cacheThe time interval of the cache element




Set inopen_file_cacheInstructioninactiveDuring the timeout time of the parameter configuration, the file should be accessed to the minimum number of times。
If the number of access is greater than equal to this value,The file description will be retained in the cache,Otherwise, delete from the cache。

(website development hsn code)1


(website development hsn code)error_log

Wrong access request log record,When the concurrency is bigNginxThe preservation of the access log and the wrong log will definitely cause a large number of reads and writing to the disk to also affectNginxPerformance

Note or The error log is set to error or crit



Successful access to request log record, If the log must be saved,You can cut the logs daily or every time or other times,This can also be reducedIO,Although the possible effect is not particularly large,But because the size of the log file has become smaller,It is also convenient for consulting or archiving analysis logs

It is recommended to open the logging level main



By defaultgzipCompression function:IncreaseCPUTreatment time and load(Just default)
closuregzipCompression function:Although the decrease is reducedCPUCalculate the response time of the server,However, the overall response time on the website page increases the data transmission time of static file data;

set up gzip on To;(There are attached parameters in this module)



The time of free and long connection keeps open;The established before reuseTCPConnect to receive request、Send a response,Reduce re -establishmentTCPConnected resource overhead

The positive number is to open the lasting connection(Conventional settings120)and0closure。
When the content of the website page is mainly static,Open a long -lasting connection;
Dynamic web pages and not being converted into static pages,Then turn off the lasting connection;



The number of requests that can be requested by a single client can be requested, but when using the pressure test tool to send multiple request tests from one client,This value is more useful to be more useful

(website development hsn code)The default value is100



Browser cache settingsHTTPResponse“Expires”and“Cache-Control”Head standard。"Expires"General combination"Last-Modified"Use comparison time,Avoid transmitting file content from the server to reduce the server pressure,Save bandwidth and increase the speed of user access

-1 Indicates that it will not be caught forever,Recommend static files such asjs/cssWait for access settings expires 30da;

4.Safety configuration#

describe:NginxSafety issues caused by inappropriate security configuration,NginxThere are some security problems in the default configuration,For example, version number information leakage、UnopenedSSLProtocol et al。
rightNginxSafety configuration can effectively prevent some common safety issues,Do a good job of security configuration in accordance with the baseline standard can reduce the occurrence of security incidents,GuaranteeNginxServer system application is safely running;

NginxSecurity configuration item:

0.hidenginxService and version

Tips: After modifying the corresponding source code file。

#vi nginx-1.9.11/src/http/ngx_http_header_filter_module.c
static char ngx_http_server_string[] = "Server: LTWS" ; #Modification
#vi nginx-1.9.11/src/http/ngx_http_special_response.c
static u_char ngx_http_error_full_tail[] =
"<center> NGINX_VER </center>" 

static u_char ngx_http_error_tail[] =

#Set the response front version version
#vim src/core/nginx.h
#define NGINX_VERSION      "secWaf"            #Can be changed to the version number you want
#define NGINX_VER          "1.1" NGINX_VERSION #Change to your service name
website development hsn code

After the setting is successful, verification:

website development hsn code

1.Low power user operation service

Should be configuredrootLow power users to runnginxServe,Set up as followsNginxUser group and user,useuserInstruction refers to running users

Reinforcement method:

groupadd nginxweb;
useradd -M -g nginxweb -s /sbin/nologin nginxweb 

#nginx.conf Medium configuration Or compile Specify when
#nginx Install compile parameter--user=nginx --group=nginx
user nginxweb

2.ConfigurationSSLAnd its session reuse

(website development hsn code)We should configure the site we provideSecure Sockets Layer Protocol (SSLprotocol),Configure it for the security of data transmission,SSLRelying on certificates to verify the identity of the server,And encrypted communication between the browser and the server。

(website development hsn code)server {
  # Open SSL and http2 support
  listen 443 ssl http2;
  listen [::]:443 ssl http2;
  # Open SSL ,If you wanthttp and https Public use of a configuration can comment on it( the "ssl" directive is deprecated )
  # ssl on;

  # Configure certificate chain and certificate key
  ssl_certificate      /etc/nginx/ssl/fullchain.cer;
  ssl_certificate_key  /etc/nginx/ssl/;

  # sslDemocratic timeout time and session duplicate cache size
  ssl_session_timeout 1d;
  ssl_session_cache shared:MozSSL:10m;  # about 40000 sessions

3.limitSSLProtocol and encryption kit

It should not be used unsafeSSLv2、SSLv3The agreement is the following and the vulnerable encryption kit(ciphers), We should use newer oneTLSThe agreement should also be better than the old ones,And use a secure encryption kit。

# Compatibility is more commonSSLProtocol and encryption algorithm kit
ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;

# Browser client automatic negotiation encryption kit(For compatibility)
ssl_prefer_server_ciphers  on;

4.Intercepting spam information

HTTP Referrer SpamIt is the Internet search engine that is used to improve the website of the website that they are trying to promote the promotion.,If their spam link is displayed in the access log,And these logs are scanned by search engines,It will have a adverse effect on the website ranking
Reinforcement method:

if ( $http_referer ~* (babes|forsale|girl|jewelry|love|nudit|organic|poker|porn|sex|teen) ){
  return 403;

5.Malicious scan interception

Use the scanner to scan when the malicious attacker uses a scanneruse-agentDetermine whether it is a commonly used tool scan and a specific version,Yes, it returns an error or redirect;

# Block alluser-agent
if ($http_user_agent ~* "java|python|perl|ruby|curl|bash|echo|uname|base64|decode|md5sum|select|concat|httprequest|httpclient|nmap|scan|nessus|wvs" ) {
    return 403;

if ($http_user_agent ~* "" ) {
    return 403;

# The expansion name of the specific file is blocked, such as.bakAnd directory;
location ~* \.(bak|swp|save|sh|sql|mdb|svn|git|old)$ {
  rewrite ^/(.*)$  $host  permanent;
location /(admin|phpadmin|status)	{ deny all; }
website development hsn code

(website development hsn code)


(website development hsn code)Nginxsupportwebdav,Although it will not compile by default。If usedwebdav,It should beNginxDisable this rule in strategy。
Reinforcement method: dav_methods It should be set tooff

7.DisableNginxState module

(website development hsn code)When visiting a specialURLTime,Such as"../nginx.status",stub_statusThe module provides a short oneNginxServer status summary,This module should not be enabled in most cases。
Reinforcement method:nginx.confIn the filestub_statusShould not be set to:on

8.Turn off the default error pageNginxversion number

If you appear in the browserNginxAutomatic error message,By default, it will includeNginxVersion number,This information can be used by attackers to help them discover the potential vulnerabilities of the server
Reinforcement method: closure"Server"The output of the response headerNginxVersion numberserver_tokensIt should be set to:off

server_tokens off 

9.set upclient_body_timeouttime out

client_body_timeoutSet the request body(request body)Reading timeout time。Just oncereadstepmiddle,No request body,It will be set to timeout。After timeoutNginxreturnHTTPstatus code408(Request timed out)。
Reinforcement method:nginx.confIn the fileclient_body_timeoutIt should be set to:10

10.set upclient_header_timeout

client_header_timeoutSet up and waitclientSend the timeout of a request header(E.g:GET / HTTP/1.1)。Just oncereadI did not receive the request header,Only set to timeout。After timeoutNginxreturnHTTPstatus code408(Request timed out)。

Reinforcement method:nginx.confIn the fileclient_header_timeoutIt should be set to:10

(website development hsn code)

11.set upkeepalive_timeouttime out

keepalive_timeoutSet andclientofkeep-aliveConnection timeout time。The server will close the connection after this time。

Reinforcement method:nginx.confIn the filekeepalive_timeoutIt should be set to:55

12.set upsend_timeouttime out

(website development hsn code)send_timeoutSet the client's response timeout time。This settings will not be used for the entire forwarder,Instead。If this period of time,The client does not read any data,NginxWill turn off the connection。

Reinforcement method:nginx.confIn the filesend_timeoutIt should be set to:10

13.NginxAvailable methods should be limited asGET, HEAD, POST

(website development hsn code)GETandPOSTYesInternetThe most commonly used method。WebThe server method isRFC 2616Definition is prohibited.。

Reinforcement method:

#nginx.confThere should be in the file
if ($request_method !~ ^(GET|HEAD|POST)$ )

14.Control concurrent connectionlimit_zone slimits

limit_zone Configuration items limit the number of connections from the client while the number of connections。Through this module, you can connect the number or special situation of the connection or special situation from a address to limit the session.。

Reinforcement method:nginx.confIn the filelimit_zoneIt should be set to:slimits $binary_remote_addr 5m

# Set to save each key(E.g$binary_remote_addr)The parameters of the shared memory space of the state,zone=Spatial name:Calculation of size and size is related to variables
limit_conn_zone $binary_remote_addr zone=ops:10m;

15.Control concurrent connectionlimit_conn slimits

This configuration item controls the maximum number of sessions connected at the same time,That is, limit from a singleIPThe number of connections of the address。

Reinforcement method:nginx.conf In the file limit_conn It should be set to: slimits 5

(website development hsn code)# Indicate the sameIPOnly allowed at the same time10Connection
limit_conn ops 5;

16.Host defensewebshellCross -view viewing and column directory

Reinforcement method:

a.existnginx.confDifferent from each virtual host site request port
b.Build one for each siteconf,Configure
d.Start service

#existmain-http-serverSet in the section to open or close(For those who need a list of directory, open,Otherwise, it is closed by default)
autoindex off

17.File name analysis vulnerabilityphp_info,join infcgi.confTo

if ($request_filename ~* (.*)\.php) {
    set $php_url $1;

if (!-e $php_url.php) {
    return 403;

18.Access permissions controlnginx

Reinforcement method:

location ~ ^/script/ {
    auth_basic "welcome to";
    auth_basic_user_file /var/www/test/script/.htpasswd;

#EstablishhtpasswdCode authentication
mkdir /var/www/test/script
perl -e "print crypt('baidu.eud',"n");"

echo 'nginx:nnUygd3RSf3u6' > /var/www/test/script/.htpasswd
/usr/local/nginx/sbin/nginx -s reload
website development hsn code

(website development hsn code)

19.Back to abnormal state200hideURL

(website development hsn code)Solution:

  listen       80;
  index index.html index.htm index.php;
  root  /data/web;
  error_page 404 =200 /404.jpg;

20.Selection of security modules

# Security detection module selection

21.Record the visitor trueIP

(website development hsn code)Describe back -end acquisitionProxyLater trueClientofIPGetting needs to be installed--with-http_realip_module,Then the back -end program is adoptedJAVA(request.getAttribute("X-Real-IP"))Obtain;

set_real_ip_from;#(Here is the known agentip)
real_ip_header X-Forwarded-For;
real_ip_recursive on;

# Proxy
location / {

proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
set $Real $http_x_forwarded_for;
if ( $Real ~ (\d+)\.(\d+)\.(\d+)\.(\d+),(.*) ){
    set $Real $1.$2.$3.$4;
proxy_set_header X-Real-IP $remote_addr;

#the difference
$proxy_add_x_forwarded_for #One more than the following$remote_addrof(You can only get the upper -level request directly connected to the server itselfip)

#Log acquisition
$http_x_real_ip|$remote_addr  #the Prerequisite iscdn There are also settings over thereX-forwardOtherwisecdnofip

22.Regional access response measures

describe: If you want to usegeoipRegional selection,We need againnginxJoin when compiling --with-http_geoip_module Compile parameter。

# E.g,VisitorIPThe address is not returned to both China or the United States403。
if ( $geoip_country_code !~  ^(CN|US)$ ) {
  return 403;

23.Resource anti -theft chain settings

describe: To prevent external sites from quoting our static resources,We need to set those domain names to access our static resources。

# none : "Referer" The source of the source is empty
# blocked : "Referer" The source head is not empty
# server_names : "Referer"The source head contains the current oneserver_names(Current domain name)
location ~* \.(gif|jpg|png|swf|flv)$ { 
  valid_referers none blocked server_names ~\.google\. ~\.baidu\.; #This is a domain name orIPaddress,Generally, it cangoogle,baidu,sogou,soso,bing,feedsky,zhuaxia,photozeroWait for the domain name
  if ($invalid_referer) { 
    #This setting can be a anti -theft chain,continuously302Rectify many times,May increase the burden on the server,So it is not recommended to do this,Unless there is a separate picture server support
    return 403; # Or return 403 error code or JSON String

    # returnjson
    add_header Content-Type 'application/json; charset=utf-8';
    return 200 "{'msg':'valid'}"; 
    # Local directory rewrite
    rewrite ^/.*.(gif|jpg|jpeg|png)$ /static/qrcode.jpg last;
    # Rewrite remoteURL
    rewrite ^/;


(website development hsn code)

24.Conventional safety response head configuration

describe: I have collected belowWebThe conventional security response header in the service, It can guarantee not to be attacked,Suggesting server{} Code block configuration。

# HSTS (ngx_http_headers_module is required) Should only be used HTTPS Instead of using HTTP Communicate
add_header Strict-Transport-Security "max-age=31536000;includeSubDomains;preload" always;

# XXS-Protection
add_header X-XSS-Protection "1; mode=block";

# MIME Simulation detection
add_header X-Content-Type-Options nosniff;

# Frame safely control
add_header X-Frame-Options ALLOW-FROM;

# Spider Robots Crazy Restrictions
add_header X-Robots-Tag none;

# CORS Cross -domain settings
add_header Access-Control-Allow-Origin '*';
add_header Access-Control-Allow-Methods 'GET';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

# Now let us allow self -hosting scripts、images、CSS、fonts and AJAX,as well as jQuery CDN Host script and Google Analytics Content:
Content-Security-Policy: default-src 'none'; script-src 'self'; img-src 'self'; connect-src 'self'; font-src 'self'; style-src 'self';

(website development hsn code)

25.Prevent non -affiliated domain name analysis to the server

describe: In order to prevent some unpacking domain names or malicious mirroring stations, the domain name is bound to our server, As a result, the server was warned to shut down,Will be on business orSEORanking and corporate image affect,We can prevent in the following ways。

(website development hsn code)server {
  listen 80 default_server;
  # Forbidden search engine to includeIP
  add_header X-Robots-Tag 'noindex,noarchive,nosnippet';
  location ^~ / {
    # IPAddress access compulsory301Jump
    if ( $host = ){
      return 301;
    # askhostBack when non -specified domain namejson
    if ( $host !~* weiyigeek\.top ) {
      add_header Content-Type 'application/json; charset=utf-8';
      return 200 '{"status":"error","Author":"WeiyiGeek","Site":"","Chinese":"Big guy, Please do not analyze your domain name to my server","English":"Friend, Please do not resolve your domain name to my server"}';
      # return 301;

(website development hsn code)Results of the:

$ curl -I
HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Mon, 11 Apr 2022 12:15:02 GMT
Content-Type: text/html
Content-Length: 162
Connection: keep-alive
X-Robots-Tag: noindex,noarchive,nosnippet

$ curl --insecure -I
HTTP/2 301
server: nginx
date: Mon, 11 Apr 2022 12:15:24 GMT
content-type: text/html
content-length: 162
x-robots-tag: noindex,noarchive,nosnippet

$ curl
{"status":"error","Author":"WeiyiGeek","Site":"","Chinese":"Big guy, Please do not analyze your domain name to my server","English":"Friend, Please do not resolve your domain name to my server"}

25.Limit the designated client address access

describe: Sometimes your website may only need to be one of the oneIPorIPThe address of the paragraph request access,Then the address access in the non -white list will be prevented from visiting, We can configure the following;

location / {
  deny  all;

5.Configuration instructions#

Commonly usednginxConfiguration file explanation:

#[Main] NginxStarted users(Suggestionrootuser)
user nginx;

#[Main] NGINXWork process number setting value and value andCPUThe core number is consistent(Optimization option)
#use grep ^processor /proc/cpuinfo | wc -l Check orauto
worker_processes  auto;

#[Main] The upper limit of the working mode and the number of connections, that is, the maximum number of connections that can be processed in each work process(Optimization option)
events {
    #[Main-events] nginxAs the maximum number of connections of a single process of reverse proxy server(Maximum connection number=Number of connections*Process number)
    #Proposal andworker_rlimit_nofileConsistent
    worker_connections  65535;
    #[Main-events] use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; 
    #epollModelLinux 2.6The high -performance network in the above version of the kernelI/OModel,If you runFreeBSDabove,then applykqueueModel。
    use epoll;
    #[Main-events] Improve performance and throughput
    accept_mutex off;

#[Main] High and hair parameter(SetcpuDecorative decreaseCPUPerformance loss caused by on -site reconstruction caused by nuclear switching registers)(Optimization option)
worker_cpu_affinity 0001 0010 0100 1000; #When the quad -core
#If it is8 cpu As follows: worker_cpu_affinity 00000001 00000010 00000100 00001000 0001000000100000 01000000 10000000

#[Main] There is no setting by default,Can limit the maximum restrictions of the operating system65535。(Optimization option)
worker_rlimit_nofile 65535

#[Main]Log position and log level[ debug | info | notice | warn | error | crit ]
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
error_log logs/error.log  error;

#Service process startup file
pid /var/run/;

#The current main configuration file contains othersnginxModule configuration file
include /etc/nginx/conf.d/*.conf; 

#[Mainpart] httpServer provisionhttpSome configuration parameters related to the service。E.g:use or notkeepalivewhat,use or notgzipCompress。
http {
    #File extension and file type mapping table
    include       mime.types;
    #Default file type
    default_type  text/html;
    #Code format of response
    charset UTF-8;
    #Server namehashTable size
    server_names_hash_bucket_size   128;
    #The maximum number of bytes requested by the buffer agency buffer user terminal, 
    client_body_buffer_size 128k
    #Upload file size restriction
    client_header_buffer_size 4k;
    #The maximum number of bytes that allow the client to request。If there is a larger file upload,Please set its limit value
    client_max_body_size 10m

    #The file access cache setting is consistent with the system file description setting
    open_file_cache max=65536  inactive=60s;
    open_file_cache_valid      80s;
    open_file_cache_min_uses   1;

    large_client_header_buffers 4 64k; #Set the request slow

    #nginxLogging format
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                     '"$http_user_agent" "$http_x_forwarded_for"';

    #Use buffer instead of each log record to perform writing operation separately,NGINXCan buffer a series of log records using a single operation to write them together into the file together。
    access_log  logs/access.log  main buffer=1024 flush=60s;

    #closureserverInformation head response
    server_tokens off;

    #[MAIN-http]Enter the efficient file transmission mode,SpecifynginxWhether to callsendfileFunction to output files,Reduce the context of user space to the kernel space(andaccept_mutexAssociated configuration)
    #For ordinary applications on,If it is used to download and other application disksIOThe heavy load application can be set to be set tooff,To balance disk and networkI/OProcessing speed,Reduce the load of the system。
    #The system calls the data copy from one file descriptor to another file descriptor,Normally zero copies are implemented,This can accelerateTCPdata transmission
    #When the configuration environment issendfileInstructions and activation content changes the instructions of the filterNGINXIt will automatically disablesendfile。#(Optimization option)
    sendfile        on; 
    #Prevent network obstruction,But to includekeepalivedThe parameter is effective
    tcp_nopush on; 
    tcp_nodelay on; 

    #The time of free and long connection keeps open(Optimization option)
    #When a long connection request a large number of small files,Can reduce the overhead of the reconstruction connection,But if there is a large file upload120sIf the inside is not uploaded, it will lead to failure。If the setting time is too long,There are many users,Keeping a large amount of resources for a long time will occupy a lot of resources。
    keepalive_timeout  120;
    #Used to specify the timeout of the response client。This timeout is limited to the time between two connection activities,If there is no activity if the client exceeds this time,NginxWill close the connection
    #send_timeout  180s
    #OpengzipCompression output,Reduce network transmission。
    gzip  on;
    #Minimum compression file size(Be careful not to be less than1k)
    gzip_min_length 1k;
    #Compressed buffer
    gzip_buffers 4 64k;
    #Compressed version(default1.1,If the front end issquid2.5please use1.0)
    gzip_http_version 1.1;
    #Compression level
    gzip_comp_level 2;
    ##Compression,By default, it already includestext/html,
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
    #FastCGIThe related parameters are to improve the performance of the website:Reduce resource occupation,Improve access speed。
    # fastcgi_temp_path  /tmp/fastcgi_temp;
    # fastcgi_cache_path /tmp/fastcgi_cache levels=1:2 keys_zone=cache_fastcgi:128m inactive=30m max_size=1g;
    # fastcgi_cache_key  $host$request_uri;
    #designatedHttpStatus code specify cache time
    # fastcgi_cache_valid 200 302 1h; 
    # fastcgi_cache_valid 301 1d;
    # fastcgi_cache_valid any 1m;
    # fastcgi_cache_min_uses 1;
    # fastcgi_cache_use_stale error timeout http_500 http_503 invalid_header;
    #Specify the link to the back endFastCGITimeout time。
    # fastcgi_connect_timeout 300;
    #TowardsFastCGIThe timeout of the transmission request,This value refers to the two handshake that have been completed twiceFastCGIThe timeout of the transmission request。
    # fastcgi_send_timeout 300;
    #Specify receivingFastCGIAnswer timeout,This value means that you have completed two handshake and receiveFastCGIAnswer timeout。
    # fastcgi_read_timeout 300;
    #Specify readingFastCGIHow much buffer needs to be used in the first part of the answer,This value means that it will be used1indivual64KBThe first part of the buffer read the response(Response),Can be set togastcgi_buffersThe size specified by the options。
    # fastcgi_buffer_size 64k;
    #onephpThe page size generated by the script is256KB,Then it will allocate4indivual64KBCushion to cache
    # fastcgi_buffers 4 64k; 
    #Suggest set tofastcgi_bufferTwice,Busy timebuffer
    # fastcgi_busy_buffers_size 128k;
    # fastcgi_temp_file_write_size 128k;

    #[Main-http]Configure virtual host settings
    #httpSupport several virtual hosts in the service。Each virtual host has a correspondingserverConfiguration item,The configuration item contains the configuration of the virtual host
    server {
        #[Main-http-server] ngnixListening port
        listen       80;
        #server name:The domain name of the virtual host can write multiple domain names,Can be matched by regular。
        server_name  localhost;

        #Realize accesshttpAutomatically jump tohttps
        return 301 https://$host$request_uri;
        #access_log  logs/host.access.log  main;

        #Request to determine the access path with regular matching,Default visitlocalhost:80 Access is the webpage of the following path
        location / {
            #Site root directory where your website file stores
            root   html;
            #Define the file name of the default access under the path,Usually followrootput
            index  index.html index.htm;
            #Open restrictionIPNeed to use it when the number of connections
            #limit_zone crawler $binary_remote_addr 10m; 

            #Access control module will be installed by default,And the writing is very simple,Can there be multipleallow,deny,Allow or prohibit a certainiporipParagraph,
            #If you meet any rules in turn, stop matching (Security Options)
            deny all;
            #Authentication passhttpd-devel Tool htpasswd Set the login password for the access path (Security Options)
            #for example:htpasswd -c nginx.htpasswd admin Generate default useCRYPTEncrypted password file#
            auth_basic "Nginx Status"
            auth_basic_user_file /usr/local/nginx/nginx.passwd
            #List the directory autoindex NginxThe default is the right download server that is not allowed to list the entire directory。(Very not recommended)
            #If you need this feature,Opennginx.confdocument,existlocation,server or httpAdd in the paragraphautoindex on;
            #autoindex on
            #The exact size unit of the file isbytes。Change tooffLater, the file is about the approximate size of the file,UnitkBorMBorGB
            #autoindex_exact_size off
            #The default isoff,Display file time isGMTtime。Change toonback,The displayed file time is the server time of the file
            #autoindex_localtime on;
        #error_page  404              /404.html;
        #Direct the server error page directly to the static page/50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;

        #actingPHPScriptApachePrison127.0.0.1:80 At the endphporphp5Ending
        #location ~ \.(php|php5)?$ {
        #    proxy_pass;

        #WillPHPScript transmission to monitoring127.0.0.1:9000ofFastCGIserver
        #location ~ .+\.(php|php5)$ {
        #    root           html;
        #    fastcgi_pass;
        #    fastcgi_pass   unix:/tmp/php.sock;  #For security recommendations
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #    fastcgi_cache  cache_fastcgi;

        # ifApacheDocument roots and listsnginxThe root directory is consistent,Then refuse to visit.htaccessdocument
        #location ~ /\.ht {
        #    deny  all;
        #Static resource regular request path matching
        location ~ .+\.(gif|jpg|jpeg|png|bmp|swf|txt|csv|doc|docx|xls|xlsx|ppt|pptx|flv)$ {  
          root  e:wwwroot; 
          expires 30d;  #Cache validity period30sky
          access_log off; #Access to records
        #JSandCSSCache time settings
        location ~ .+\.(js|css|html|xml)$ { expires 30d;}

        #Access control can also be added to authentication
        location /nginx-status{
            #nginxmiddlestub_statusModule is mainly used to viewNginxSome status information. This module is not installed in this module to be compiled and installed。
            stub_status on;
            deny all;
    #### NginxReverse agent ######
    #[Main-http] upstreamThe internal interior of the module sets the connection between the reverse proxy and the load balancingwebApplication serviceIPport
    upstream monitor_server {
        #seesionRecord the host of the access,For example, after visiting the server for the first time,After that, the server is the server-Bind
        #Application service of internal network,weigthThe higher the parameter, the greater the chance of being assigned to。
        #max_failsShouldmax_failsFailure for a request,It means that the back -end server is not available,The default is1Set it to0Can close the check 
        #fail_timeout In the futurefail_timeoutin timenginxI will no longer send the request to the server that has been checked as an unavailable server 
        server weight=9 max_fails=5 fail_timeout=600s;  
        server weight=1 max_fails=5 fail_timeout=600s;
    #serverInstruction configuration item
    server { 
        listen 80; 
        #Domain name of request response
        location / {
          ##### Modulehttp_proxy:##### Reverse proxy main configuration
          #Inverse proxy,correspondupstreamLoad balancer
          proxy_pass http://monitor_server;
          #Proxy server -related information header settings
          proxy_redirect off;
          #If it is involvedredirectService,Be sure to add ports8081,no The defaulttomcatexistredirectTime to find80port 
          proxy_set_header Host $host;
          #Forward the originalIPaddress,Pass in the programrequest.getHeader("Proxy-Client-IP")getip 
          proxy_set_header X-Real-IP $remote_addr;
          #EndlessWebThe server can passX-Forwarded-ForGet user truthIP
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
          ##nginxConnect to the back -end server timeout time(Proxy connection timeout)
          #Modulehttp_proxyProxy timeout settings
          proxy_connect_timeout 60s;  
          ##nginxConnect to the back -end server timeout time(Proxy connection timeout) 
          proxy_read_timeout 60s;     
          #Back -end server data return time(Proxy timeout) between
          proxy_send_timeout 30s;
          #Set the proxy server(nginx)From the back endrealserverThe size of the buffer of the user head information,Default andproxy_buffersThe same size,In fact, you can set this instruction value
          proxy_buffer_size 4k
          #proxy_buffersBuffer,nginxFor a single connection cache from the back endrealserverthe response to,The webpage is on average32kbelow
          proxy_buffers 4 32k
          #High load down buffer size(proxy_buffers*2)
          proxy_busy_buffers_size 64k
          #whenproxy_buffersWhen the response content of the back -end server cannot be put down,Will save part of the temporary file of the hard disk,This value is set to set the maximum temporary file size,default1024M
          #It andproxy_cacheNot to do。Greater than this value,FromupstreamServer return。Set as0Disable。
          proxy_max_temp_file_size 0
          #When the server where the cache is agent responds to the temporary file,Limit the size of the temporary file each time。proxy_temp_path(You can compile)Specify which directory to write。
          proxy_temp_file_write_size 64k

          #BundlecookieThe role of the domain is replaced by our domain name。
          #proxy_set_header Host "";          #Set up reverse proxyheaderRequest
          #proxy_redirect ;          #Redirect
          #proxy_redirect http:// https://;
          #sub_filter;       #Replace Google's domain name with your own,Pay attention to installationnginxofsub_filterModule
          #Configuration of reverse proxy. END

        #Local static separation reverse proxy configuration
        #alljspThe pages of the pages are attached totomcatorresindeal with
        location ~ .(jsp|jspx|do)?$ {
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        #All static filesnginxRead directly without passingtomcatorresin
        location ~ \.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$ { expires 15d; }

        location ~ \.(js|css)$ { expires 1h; }

    # Another virtual host,Mixed useIP、Name and port -based configuration
    server {
      listen 80;
      listen [::]:80;
      return 301 https://$host$request_uri;

    server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    # HSTS (ngx_http_headers_module is required) Should only be used HTTPS Instead of using HTTP Communicate
    add_header Strict-Transport-Security "max-age=31536000;includeSubDomains;preload" always;

    # XXS-Protection
    add_header X-XSS-Protection "1; mode=block";

    # MIME Simulation detection
    add_header X-Content-Type-Options nosniff;

    # Frame safely control
    add_header X-Frame-Options ALLOW-FROM;

    # Spider Robots Crazy Restrictions
    # add_header X-Robots-Tag none; # not limited
    # add_header X-Robots-Tag noindex, noarchive, nosnippet; # limit

    # Open SSL ,If you wanthttp and https Public use of a configuration can comment on it( the "ssl" directive is deprecated )
    # ssl on;

    # Configure certificate chain and certificate key
    ssl_certificate      /etc/nginx/ssl/fullchain.cer;
    ssl_certificate_key  /etc/nginx/ssl/;

    # sslDemocratic timeout time and session duplicate cache size
    ssl_session_timeout 1d;
    ssl_session_cache shared:MozSSL:10m;  # about 40000 sessions

    # Turn on when configured the dual certificate, otherwise it should be closed
    ssl_session_tickets off;  

    ## OCSP stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    # Root CA And intermediate certificate verification OCSP Response Trust Chain
    ssl_trusted_certificate /etc/nginx/ssl/ca.cer;

    # Use onlyECDHNo configurationssl_dhparamOtherwise you should configure it for it 
    # curl > /path/to/dhparam
    ssl_dhparam /path/to/dhparam;

    # Compatibility is more commonSSLProtocol and encryption algorithm kit
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
    # Safety configuration: ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4:!DH:!DHE;
    # A total of 18 certificates of handshake plus algorithm algorithm,ECDHE、DHE、AESStart separately6indivual
    # Recommend the server to automatically choose the algorithm kit to be used for compatibility
    ssl_prefer_server_ciphers  on;

    # replace with the IP address of your resolver


(1) Provided by AlibabaConcatorGoogleofPageSpeedModule implements the function of this merging file。

  • ConcatSource code website:
  • PageSpeedSource code website:。

(2) PHP-FPMOptimization
If you use a high load websitePHP-FPMmanageFastCGIforPHP-FPMOptimization is very important

  • 1.IncreaseFastCGIProcess number:BundlePHP FastCGISub -process number to be adjusted to100or above,exist4GMemory server200It can be recommended to obtain the best value through stress testing。
  • 2.Increase PHP-FPMOpen the limitation of the descriptor of the file
# vi /path/to/php-fpm.conf
turn up“1024”,Bundle1024change to 4096 Or higher,Repeat PHP-FPM
# /etc/security/limits.conf
* hard nofile 65536
* soft nofile 65536
  • 3.Increase appropriatelymax_requests: Labelmax_requestsEach onechildrenAfter the maximum processing of the request, the default setting will be closed after500。

(3) ConfigurationResin on LinuxorWindowsCan open for us resin-3.1.9/bin/ Add in places where other code does not affect other code:-Dhttps.protocols=TLSv1.2, E.g

exec $JAVA_EXE -jar  -Dhttps.protocols=TLSv1.2 ${RESIN_HOME}/lib/resin.jar $*
#exec $JAVA_EXE -jar  ${RESIN_HOME}/lib/resin.jar $*

(website development hsn code)Original address: