Nginx configuration file resolution (optimized)

Source: Internet
Author: User
Tags sendfile

Nginx configuration file resolution (optimized)

The Configuration File Settings include:

Main global settings
Server Host settings
Upstream Server Load balancer settings
Location is used to match webpage settings
Link: server inherits main;
Location inherits server;
Upstream will not inherit or be inherited


1. user nginx1;

# Run users and groups. The default user is nobody;

Nginx1 10820 10787 0? 00:00:00 nginx:


2. worker_processes 16;

# Number of worker processes. We recommend that you set it to equal to the total number of CPU cores.


Observe worker_processes during ps-ef

3. worker_rlimit_nofile 4096;

# Number of file handles opened by each process = Total number of systems/4 do not set to 65535

4. error_log/usr/log/nginxa1/logs/error. log warn;
# Path for storing global error logs; Level: debug | info | notice | warn | error | crit

5. pid logs/nginx. pid;

# Pid file;

6. # working mode and maximum number of connections
Events {
# The maximum number of connections for each process. Do not change it to 65535;
Worker_connections 4096;
# Use epoll (linux2.6 High-Performance Mode)
Use epoll;
}

# Refer to the event model. use [kqueue | rtsig | epoll |/dev/poll | select | poll]. The epoll model is a high-performance network I/O model in the kernel of Linux 2.6 or later versions, if you run on FreeBSD, use the kqueue model.
# Use epoll (linux2.6 High-Performance Mode)

7. # Set the http tag and use its reverse proxy function to provide Load Balancing support
Http {
# File media type requested by mimie. types Browser

Include mime. types;

# Indicates the file media type requested by the browser.

Default_type application/octet-stream;
# Set the log format
Log_format main '$ remote_addr-$ remote_user [$ time_local] "$ request "'
'$ Status $ body_bytes_sent "$ http_referer "'
'"$ Http_user_agent" "$ http_x_forwarded_for "';

$ Remote_addr direct client address
$ Http_x_forwarded_for indirect client address (usually there is a proxy server before)
$ Remote_user remote client User Name
$ Time_local records the access time and time zone
$ Request the user's request, using the HTTP protocol
$ Status return status, 200,404,304, etc.
$ Body_bytes_sents number of body Bytes Sent
$ Http_referer reference page (from which the link is accessed)
$ Http_user_agent client browser


# Setting request logs
Access_log/usr/log/nginxa1/logs/access. log main;



# Include command, which can contain any configuration file you want to include and supports file name matching.
# Include extra/bbs. conf; [root @ client scripts] # cat cut_log.sh

# Sample log cutting script:

Cd/application/nginx/logs
Mv www_access.log www_access _ $ (date + % F-d-1day). log
/Application/nginx/sbin/nginx-s reload
[Root @ client scripts] # crontab-l | tail-2
# Cut nginx log by day by oldboy at 201409
00 00 ***/bin/sh/server/scripts/cut_log.sh>/dev/null 2> & 1

# Log analysis software: syslog, rsyslog, Awstats (svn document), flume, logstash, scrilbe, kafka,
 



8. Set Request Buffer


# Buffer size of the Received header
Client_header_buffer_size 128 k;

This command is used to set the size of the Header Buffer for client requests. The default value is 4 kb.

Large_client_header_buffers 4 256 k;


# Client package buffer size
Client_body_buffer_size 1024 k;


# Set the size of files that can be uploaded by the client. The default value is 1 MB.

Client_max_body_size 8 m;





Sendfile on;

# Enable the efficient file transmission mode. The sendfile command specifies whether or not nginx calls the sendfile function to output files. For general applications, set it to on. If it is used for downloading and other application disk I/O heavy load applications, it can be set to off to balance the disk and network I/O processing speed and reduce the system load. Note: If the image is not displayed properly, change it to off.

# Enable directory list access, which is suitable for downloading the server. It is disabled by default.

Autoindex on;

# Preventing network congestion

Tcp_nopush on;

# Preventing network congestion

Tcp_nodelay on;

# Long connection timeout time, in seconds

Keepalive_timeout 120;


# Default encoding
# Charset GBK;


# Persistent connection persistence
Keepalive_timeout 120;


# Do not display Nginx version
Server_tokens off;



# Size of the hash table of the server name

Server_names_hash_bucket_size 64;
Server_names_hash_max_size: 512

 

9. # To enable the gzip module, you must specify
Gzip on;


# Minimum compressed file size, 0 by default
Gzip_min_length 1100;



# Compression Buffer
Gzip_buffers 4 16 k;


# Compression type
Gzip_types text/plain application/x-javascript text/css application/xml;



# Compression ratio: 1. The minimum compression ratio is the fastest; 9. The maximum compression ratio and fast transmission speed are low, which consumes cpu resources;
Gzip_comp_level 9;


# Compressing all files through proxy
Gzip_proxied any;
# Vary header support

# Front-end service cache Compression

Gzip_vary on;


# Compressed version (1.1 by default, 1.0 is used for the front-end squid2.5)
Gzip_http_version 1.0;


# Output buffer
Output_buffers 4 32 k;
Post pone_output 1460;

# This function is similar to the mod_deflate compression function of apache and depends on the ngx_http_gzip_module module. It is installed by default.

10. Proxy Settings;

# Proxy connection timeout
Proxy_connect_timeout 120;


# Proxy sending timeout
Proxy_send_timeouts 120;


# Proxy read timeout
Proxy_read_timeout 120;


# Set the buffer size for the response content of the proxy server from the backend
Proxy_buffer_size 512 k;


# Enable response content buffering from the back-end proxy server.
Proxy_buffering on;


# Set the buffer size and quantity of response content obtained from the proxy's backend server
Proxy_buffers 32 512 k;

# Client sending header timeout
Client_header_timeout 3 m;


# Client content Sending timeout
Client_body_timeout 3 m;


# Sending timeout to client
Send_timeout 3 m;

# Proxy_buffers buffer. The average webpage size is less than 32 KB.

Proxy_buffers 4 32 k;

# Buffer size under high load (proxy_buffers * 2)

Proxy_busy_buffers_size 64 k ;#



# Set the cache folder size. If it is greater than this value, it will be uploaded from the upstream Server

Proxy_temp_file_write_size 64 k;





Optimization of Server Load balancer sent to web_server;
The parameters are as follows:
Proxy_redirect off;
Proxy_set_header Host $ host;
Proxy_set_header X-Real-IP $ remote_addr;
Proxy_set_header X-Forwarded-For $ proxy_add_x_forwarded_for;
Client_max_body_size 50 m;
Client_body_buffer_size 256 k;
Proxy_connect_timeout 30;
Proxy_send_timeout 30;
Proxy_read_timeout 60;

Proxy_buffer_size 4 k;
Proxy_buffers 4 32 k;
Proxy_busy_buffers_size 64 k;
Proxy_temp_file_write_size 64 k;
Proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
Proxy_max_temp_file_size 128 m;
Proxy_store on;
Proxy_store_access user: rw group: rw all: r;
# Proxy_temp_path/dev/shm/nginx_proxy;
# Proxy_temp_path/data2/nginx_cache;



11. Optimize the number of processes based on the number of cpu cores;

View the number of cpu Cores
Grep "physical id"/proc/cpuinfo
Physical id: 0
Address sizes: 40 bits physical, 48 bits virtual
Physical id: 0
Address sizes: 40 bits physical, 48 bits virtual

Schedule hardware allocation
The corresponding configurations of different CPUs are as follows:
Quad-core cpu server parameter configuration:
Worker_cpu_affinity 0001 0010 0100 1000;
# The CPU affinity of nginx processes means that different processes are allocated to different CPUs for processing. Here 0001 0010 0100 1000 is a hidden code, representing 1st, 2, 3, and 4 cpu cores respectively.
Eight-core cpu server parameter configuration:
Worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;
Worker_cpu_affinity 0001 0010 0100 1000 0001 0010 0100 1000;


Taskset: Adjust cpu allocation
In addition, the (taskset-retrieve or set a process's CPU affinity) command also has the function of allocating CPU.

Example: taskset-c 1, 2, 3/etc/init. d/mysql start
MATERIALS: http://www.cnblogs.com/edwardlost/archive/2010/10/23/1858991.html



12. Adjust fastcgi parameters in seconds

Fastcgi optimization (with dynamic PHP engine Service)

Fastcgi_connect_timeout 300;
# Specify the timeout time for connecting to the backend FastCGI


Fastcgi_send_timeout 300;
# The timeout time for sending a request to FastCGI. This value refers to the timeout time for sending a request to FastCGI after two handshakes are completed.


Fastcgi_read_timeout 300;
# Specify the timeout time for receiving the FastCGI response. This value refers to the timeout time for receiving the FastCGI response after two handshakes have been completed.


Fastcgi_buffer_size 64 k;
# Specify the buffer size required to read the first part of the FastCGI response. This value indicates that the first part of the response (Response Header) will be read using a 64KB buffer ), you can set the buffer size specified by the fastcgi_buffers option.


Fastcgi_buffers 4 64 k;

# Specify how many buffers are needed locally to buffer FastCGI response requests. If the page size generated by a PHP script is kb, four 64KB buffers will be allocated for caching. If the page size is larger than kb, the part larger than kb will be cached in the path specified by fastcgi_temp, but this is not a good method, because the data processing speed in the memory is faster than the hard disk. Generally, this value should be the center value of the page size generated by the PHP script in the site. If the page size generated by most scripts on the site is 256KB, you can set this value to "16 16 K" and "4 64 K.


Fastcgi_busy_buffers_size 128 k;
# We recommend that you double the value of fastcgi_buffers.


Fastcgi_temp_file_write_size 128 k;
# The size of the data block to be used when writing fastcgi_temp_path. The default value is twice that of fastcgi_buffers. If the above value is set too long, 502 Bad Gateway may be reported when the load is on.


Fastcgi_cache oldboy_nginx
# Enable FastCGI cache and specify a name for it. Enabling the cache is very useful, which can effectively reduce the CPU load and prevent 502 errors. However, enabling the cache may also cause other problems. Select the appropriate one based on the actual situation.


Fastcgi_cache_valid 200 302 1 h;
# This parameter is used to specify the response code cache time. The value in the instance indicates that 200 and 302 are cached for an hour.


Fastcgi_cache_valid 301 1d;
# Cache 301 responses for one day


Fastcgi_cache_valid any 1 m;
# Cache other responses for 1 minute


Fastcgi_cache_min_uses 1;
# Minimum number of times cached in the inactive parameter value of the fastcgi_cache_path command

#### Process interaction generates a zero-time file


13. upstream load balancing

Upstream xxxx.xx.net {
# The weigth parameter indicates the weight. The higher the weight, the higher the probability of being allocated.
# Sru_id = a: index = 1, srun_id = B: index = 2, srun_id = c: index = 3, srun_id = d: index = 4
Server 10.110.5.81: 8081 max_fails = 3 fail_timeout = 30 s srun_id =;
Server 10.110.5.82: 8081 max_fails = 3 fail_timeout = 30 s srun_id = B;
Server 10.110.5.83: 8084 max_fails = 3 fail_timeout = 30 s srun_id = c;
Server 10.110.5.84: 8084 max_fails = 3 fail_timeout = 30 s srun_id = d;
# Ensure delivery by seesion
Jvm_route $ cookie_JSESSIONID | sessionid;
# Jvm_route $ cookie_JSESSIONID | jsessionid;
}

# Weight = NUMBER -- set the weight of the server. The higher the weight, the higher the NUMBER of allocated shards. The default weight is 1.
# Max_fails = NUMBER -- NUMBER of failed requests to the backend server within the time specified by the fail_timeout parameter. If the backend server cannot be connected or a server error occurs (except for the 404 error ), mark as failed. The default value is 1. set to 0 to disable this check.
# Fail_timeout = TIME -- the pause TIME after the number of failures set by the max_fails Parameter
# Down -- mark the server as permanently offline for ip_hash commands
# Backup -- started only when all the non-backup servers are busy

# The upstream module has the following variables:
# $ Upstream_addr: Address of the upstream server that processes the request
# $ Upstream_status: response status of the upstream Server
# $ Upstream_response_time: response time (milliseconds) of the Upstream server. Multiple responses are separated by commas (,) and colons.
# $ Upstream_http _ $ HEADER: Any http header information, for example: $ upstream_http_host


14. First Virtual Server
Server {
# Listen to port 80 of 192.168.8.x
Listen 80;

# Host name address, which can be an ip address or a host name separated by multiple Spaces
Server_name 10.10.70.x www.xxx.com;

# Define the default website root directory location of the server

Root html/bbs;

# Define the name of the home index file

Index. php index.html index.htm;

}


15. Set the status label for viewing status

Server {
Listen 80;
Server_name status.xxx.org;
Stub_status on;
Access_log off;

}
 

16. 301 redirection

Server {
Listen 80;
Server_name blog.etiantian.org;
Root html/blog;
Index index.html index.htm;
Rewrite ^/(. *) http://www.etiantian.org/#1 permanent;
}
# Access all content under the domain name to go to www.etiantian.org/before the domain name;

# IP address redirection can be used to prevent malicious domain name binding;
# Enter an ip address to access the first domain name;
#. * Indicates content; $ accept; permanent indicates permanent jump;

17. expires cache Function
# Cache the images that are being pushed to the client's browser during website operations (not frequently changed;
Advantages: reduces bandwidth, reduces server pressure, and supports high concurrency. the browser accelerates and enhances user experience;
Disadvantage: After the website and new content, the client may be old. When testing, the client will always be new, invisible, and advertisement. The statistical code is not accurate.
Solution disadvantages
Set the expiration time of expires based on business requirements;
Image Change (re-upload); time 1-10 years
Advertisement, statistics, no cache;
The website revision element should be renamed to js and css;
Cache cdn resources (** images) to clear Origin Site images. (Interface API or web Interface Management)

Example: location ~ . * \. (Gif | jpg | jpeg | png | bmp | swf) $
{
Expires 3650d;
}
Location meets the conditions for execution. Yes. Execute...
Example 2:
Location ~ . * \. (Js | css )? $
{
Expires 30d;
}
# In the server label; date-s "" modification time hwlock-c write time to the system;

 

18. Anti-leech

 

Location

# Indicates the type of file that is subject to anti-leech protection ~ . * \. (Wma | wmv | asf | mp3 | mmf | zip | rar | jpg | gif | png | swf | flv) $ {

Valid_referers none blocked * .yiibase.com yiibase.com;

# Source Judgment;

If ($ invalid_referer ){

# Rewrite ^/http://www.xxx.com/error.html;

# Return results. You can specify a specific image;

Return403 ;}

}

19. url Access Control (files, images, and ip addresses can all be set ):

Location ~ ^/Images/. * \. (php | php5) $
# Image
{
Deny all;
Location ~ ^/Static/. * \. (php | php5) $
}
{
Deny all;
}
Location ~ * ^/Data/(attachment | avatar)/. * \. (php | php5) $
# Attachment and Avatar
{
Deny all;
}


Location/admin/{return 403 ;}
Location/templates/{return 403 ;}
# Return code of the returned status; location is ordered and adjusted according to rules;

20. pseudo-static:

To be supplemented ~~!!!

21、robot.txt robot settings

View: http://www.baidu.com/robots.txt

Usage: the website's indexing probability is reduced;

Not used: reduces website resource consumption;

Example: different browser access settings:

If ($ http_user_agent ~ * "Firefox | MSIE ")
{
Return 403;
}

 

22. Prevent website trojans from being intruded

1. users and groups of all directories and files on the site should be root!
2. The default permission for all directories on the site is 755. (files cannot be stored in the directory)
3. The default permission for all files on the site is 644. (files cannot be changed)
Note that users of WebSite Services cannot use root.
Solution: Find the uploaded directory and authorize nginx to access it. This is safer!
Architecture Optimization: dynamic web clusters (three web services are supported, and each server is browsed, uploaded, and downloaded) are suitable for all web servers;
Mount optimization: mount-o nosuid, noexec, nodev

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.