Nginx environment parameter performance optimization configuration

Source: Internet
Author: User
Tags file system php script response code socket nginx server


The Old High's server recently said Alexander, who offered this article to relieve the front-end pressure and then optimized it from the code.

I. Basic configuration

Refer to the nginx configuration details of the old high.

The basic configuration only uses the basic features of nginx. We need to manually enable many advanced features!

Emphasize several configurations

# Http://nginx.org/en/docs/ngx_core_module.html#worker_processes
# Auto 1.3.8 and 1.2.5 versions are supported
Worker_processes auto;

# Optional. In the old height, set worker_processes to auto first. If worker_processes> 1 is run at the end, set this value again.
# Http://nginx.org/en/docs/ngx_core_module.html#worker_cpu_affinity
Worker_cpu_affinity 0001 0010 0100 1000;

# Check the performance settings. Related commands: ulimit-n
Worker_rlimit_nofile 60000;

Events {
# The maximum number of connections allocated to worker_processes depends on the performance of your machine.
Worker_connections 2048;
Use epoll;
}

Http {
Sendfile on;
# Tcp_nopush on;
# Tcp_nodelay on;
Keepalive_timeout 65;
Reset_timedout_connection on;
Server_tokens off;

# Limit ip
Limit_conn_zone $ binary_remote_addr zone = ip: 10 m;
# Limit server
Limit_conn_zone $ server_name zone = server: 10 m;

}

# The following restrictions are imposed on a server:
Server {
# Limit the maximum number of connections of an IP address
Limit_conn ip 3;
# Limit the maximum number of connections of a server
Limit_conn server 100;
# Speed limit
Limit_rate 100 k;
}
II. Reasonable file compression

Needless to say, JavaScript, css, and images should be compressed with corresponding compression software.

III. Enable gzip

Go directly to the old gzip configuration, and write it to the http block!

Gzip on;
# Gzip_min_length 1 k;
Gzip_min_length 0;
Gzip_buffers 4 16 k;
Gzip_comp_level 3;
Gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png app lication/ vnd. ms-fontobject application/x-font-ttf image/svg + xml;
Gzip_vary off;
Gzip_disable "MSIE [1-6] \.";
IV. Merge requests using nginx-http-concat

Project address

Nginx-http-concat

Because this module is not a standard module, you need to recompile nginx and add -- add-module =/tmp/nginx-http-concat!

Usage

Enabled in location configuration. Options and default values can be found in readme of the project.

Location/js /{
# Enable the concat function
# Disabled by default
Concat on;
# The maximum number of concat files is allowed. By default, the maximum number of files is 10.
# (Default: 10)
# Concat_max_files 10;
# Only files of the same type are allowed
# Enabled by default
# Concat_unique on;
# Allowed Content types
# (Default: application/x-javascript, text/css)
# Concat_types text/html;
}
V. Set the Expiration Time

Location ~ . * \. (Gif | jpg | jpeg | png | bmp | swf ){
Expires 30d;
}

Location ~ . * \. (Js | css ){
Expires 15d;
}
VI. proxy_cache

Use proxy_cache to cache the content generated by the backend server.

First, configure a cache space in the http block.

Proxy_cache_path/data/nginx/cache levels = 1:2 keys_zone = phpgao: 50 m inactive = 10 m max_size = 2 m;
Proxy_temp_path/data/nginx/tmp_cache;

# Number of hash directories specified by levels
# Keys_zone space name size: 10 MB space name will be used later
# Default inactive cache duration
# Max_size: maximum size of a single file
# Loader_threshold duration (unit: milliseconds, default value: 200)
# Loader_files
# The rest time after loader_sleeps reaches loader_files (unit: milliseconds; default value: 50)

After the space name is specified, we can start configuring the server.

Server {
...
...
Location /{
# If the backend server returns errors such as 502, 504, and execution timeout, the request is automatically forwarded to another server in the upstream server load balancer pool for failover.
Proxy_next_upstream http_502 http_504 error timeout invalid_header;
Proxy_cache phpgao;
# Set different cache times for different HTTP status codes
Proxy_cache_valid 200 304 12 h;
# Combine domain names, Uris, and parameters into the Key values of the Web cache. Nginx hashes the cached content to the second-level cache directory based on the Key values.
Proxy_cache_key $ host $ uri $ is_args $ args;
Proxy_set_header Host $ host;
Proxy_set_header X-Forwarded-For $ remote_addr;
Proxy_pass http: // backend_server;
Expires 1d;
    }

}
VII. fastcgi_cache

Fastcgi_cache is usually used to cache files generated by php. The configuration method is similar to proxy_cache.

Http segment:


Add_header X-Cache-CFC "$ upstream_cache_status-$ upstream_response_time ";

Fastcgi_temp_path/data/nginx/tmp_cache;
Fastcgi_cache_path/data/nginx/cache levels = 1:2 keys_zone = phpgao: 50 m inactive = 10 m max_size = 2 m;
Fastcgi_connect_timeout 300;
Fastcgi_send_timeout 300;
Fastcgi_buffer_size 64 k;
Fastcgi_buffers 4 64 k;
Fastcgi_busy_buffers_size 128 k;
Fastcgi_temp_file_write_size 128 k;
Server segment:

Server {
...
...
Location ~ . * \. (Php | php5 ){
Fastcgi_pass 127.0.0.1: 9000;
Fastcgi_index index. php;
Fastcgi_param SCRIPT_FILENAME $ document_root $ fastcgi_script_name;
Include fastcgi_params;

Fastcgi_cache phpgao;
Fastcgi_cache_valid 200 302 301 1 h;
Fastcgi_cache_valid any 1 m;
Fastcgi_cache_min_uses 1;
Fastcgi_cache_methods get head;
Fastcgi_cache_use_stale error timeout invalid_header http_500;
Fastcgi_cache_key $ request_method: // $ host $ request_uri;
    }

}
For more fastcgi configurations, refer


This module allows nginx to work with FastCGI and controls which parameters will be passed safely.
Example:
Location/{fastcgi_pass localhost: 9000; fastcgi_index index. php; your SCRIPT_FILENAME/home/www/scripts/php $ response; your QUERY_STRING $ query_string; your REQUEST_METHOD $ request_method; your CONTENT_TYPE $ content_type; fastcgi_param CONTENT_LENGTH $ content_length ;}
An instance in the cache:
Http {fastcgi_cache_path/path/to/cache levels = keys_zone = NAME: 10 m inactive = 5 m; server {location/{fastcgi_pass http: // 127.0.0.1; fastcgi_cache NAME; fastcgi_cache_valid 200 302 1 h; fastcgi_cache_valid 301 1d; fastcgi_cache_valid any 1 m; Interval 1; fastcgi_cache_use_stale error timeout invalid_header http_500 ;}}}
After 0.7.48, the Cache follows the Cache-Control and Expires of the backend server. After 0.7.66, the "Cache-Control:" private "and" no-store "headers are also followed.

· Instructions

Fastcgi_buffer_size

Syntax: fastcgi_buffer_size the_size;
Default value: fastcgi_buffer_size 4 k/8 k;
Field used: http, server, location
This parameter specifies how much buffer will be used to read the first part of the response from the FastCGI server.
Generally, this part contains a small response header.
The default buffer size is the size of each block in the fastcgi_buffers command. You can set this value to a smaller value.

Fastcgi_buffers

Syntax: fastcgi_buffers the_number is_size;
Default value: fastcgi_buffers 8 4 k/8 k;
Field used: http, server, location
This parameter specifies the number of local replies to be read from the FastCGI server and the number of large buffers. By default, this parameter is equal to the page size, which may be 4 KB depending on the environment, 8 K or 16 K.

Fastcgi_cache

Syntax: fastcgi_cache zone | off;
Default value: off
Field used: http, server, location
Specify an area for the shared memory actually used by the cache. The same area can be used in different places.

Fastcgi_cache_key

Syntax: fastcgi_cache_key line
Default value: none
Field used: http, server, location
Set cache keywords, such:
Fastcgi_cache_key localhost: 9000 $ request_uri;
Fastcgi_cache_path

Syntax: fastcgi_cache_path path [levels = m: n] keys_zone = name: size [inactive = time] [max_size = size]
Default value: none
Field used: http
The clean_time parameter has been removed in version 0.7.45.
This command specifies the FastCGI cache path and other parameters. All data is stored as files, and the cached key and file name are calculated as the MD5 value calculated by the proxy url.
The Level parameter sets the directory classification of the cache directory and the number of subdirectories. For example, if the command is set:
Fastcgi_cache_path/data/nginx/cache levels = keys_zone = one: 10 m;
Data files are stored as follows:
/Data/nginx/cache/c/29/b7f54b2df7773722d382f4809d42429c
Files in the cache are first written into a temporary file and subsequently moved to the last location of the cache directory. After version 0.8.9, temporary files and cached files can be stored in different file systems, however, you need to understand that this kind of movement is not a simple atomic rename system call, but a copy of the entire file, so it is best to use the same file system in the values of fastcgi_temp_path and fastcgi_cache_path.
In addition, all active keywords and data-related information are stored in the shared memory pool. The value name and size are specified by the key_zone parameter, and the inactive parameter specifies the data storage time in the memory, the default value is 10 minutes.
The max_size parameter sets the maximum cache value. A specified cache manager process periodically deletes old cache data.

Fastcgi_cache_methods

Syntax: fastcgi_cache_methods [get head post];
Default value: fastcgi_cache_methods get head;
Field used: main, http, location
You cannot disable GET/HEAD, even if you just set it like this:
Fastcgi_cache_methods POST;
Fastcgi_cache_min_uses

Syntax: fastcgi_cache_min_uses n
Default value: fastcgi_cache_min_uses 1
Field used: http, server, location
The command specifies how many requests the same URL will be cached.

Fastcgi_cache_use_stale

Syntax: fastcgi_cache_use_stale [updating | error | timeout | invalid_header | http_500]
Default value: fastcgi_cache_use_stale off;
Field used: http, server, location
In the case of Gateway errors or timeout, nginx will transmit expired cache data.

Fastcgi_cache_valid

Syntax: fastcgi_cache_valid [http_error_code | time]
Default value: none
Field used: http, server, location
Specify the cache time for the specified http return code, for example:
Fastcgi_cache_valid 200 302 10 m; fastcgi_cache_valid 404 1 m;
Cache the response status codes 200 and 302 for 10 minutes, and 404 for 1 minute.
By default, the cache only processes 200,301,302 of the status.
You can also use any in the command to represent any one.
Fastcgi_cache_valid 200 302 10 m; fastcgi_cache_valid 301 1 h; fastcgi_cache_valid any 1 m;
Fastcgi_connect_timeout

Syntax: fastcgi_connect_timeout time
Default value: fastcgi_connect_timeout 60
Field used: http, server, location
Specify the connection timeout time of the same FastCGI server. The value cannot exceed 75 seconds.

Fastcgi_index

Syntax: fastcgi_index file
Default value: none
Field used: http, server, location
If the URI ends with a slash, the file name is appended to the URI, and the value is stored in the variable $ fastcgi_script_name. For example:
Fastcgi_index index. php; fastcgi_param SCRIPT_FILENAME/home/www/scripts/php $ fastcgi_script_name;
Request "/page. the SCRIPT_FILENAME parameter of php is set to "/home/www/scripts/php/page. php ", but"/"is"/home/www/scripts/php/index. php ".

Fastcgi_hide_header

Syntax: fastcgi_hide_header name
Field used: http, server, location
By default, nginx does not transmit the "Status" and "X-Accel-..." headers from the FastCGI server to the client. This parameter can also hide some other headers.
If you must pass the "Status" and "X-Accel-..." headers, you must use fastcgi_pass_header to force them to be transmitted to the client.

Fastcgi_ignore_client_abort

Syntax: fastcgi_ignore_client_abort on | off
Default value: fastcgi_ignore_client_abort off
Field used: http, server, location
If the current connection request to the FastCGI server fails, you can use this command to prevent it from being disconnected from the nginx server.

Fastcgi_ignore_headers

Syntax: fastcgi_ignore_headers name [name...]
Field used: http, server, location
This command prohibits the processing of some header fields of the FastCGI server response. For example, you can specify fields such as "X-Accel-Redirect", "X-Accel-Expires ", "Expires" or "Cache-Control.

Fastcgi_intercept_errors

Syntax: fastcgi_intercept_errors on | off
Default value: fastcgi_intercept_errors off
Field used: http, server, location
This command specifies whether to transmit 4xx and 5xx error messages to the client, or allows nginx to use error_page to process error messages.
You must explicitly specify the processing method in error_page to make this parameter valid, as Igor says, "if no proper processing method is available, nginx will not block an error, this error does not display its default page. You can use some methods to block the error.

Fastcgi_max_temp_file_size

Syntax: fastcgi_max_temp_file_size 0
Default value :?
Field used :?
Disable the FastCGI buffer based on the source code.

Fastcgi_no_cache

Syntax: fastcgi_no_cache variable [...]
Default value: None
Field used: http, server, location
Determine under which circumstances the cached response will not be used, for example:
Fastcgi_no_cache $ cookie_nocache $ arg_nocache $ arg_comment; fastcgi_no_cache $ http_pragma $ http_authorization;
If it is a null string or equal to 0, the expression value is equal to false. For example, in the preceding example, if cookie "nocache" is set in the request, the cache will be bypassed.

Fastcgi_next_upstream

Syntax: fastcgi_next_upstream error | timeout | invalid_header | http_500 | http_503 | http_404 | off
Default value: fastcgi_next_upstream error timeout
Field used: http, server, location
The command specifies the situation in which the request will be forwarded to the next FastCGI server:
· Error-an error occurred when connecting to the server for a transfer request or a request that is reading the response header.
· Timeout-the transfer request or the request that is reading the response header times out when connecting to the server.
· Invalid _ header-the server returns an empty or invalid response.
· Http _ 500-the server returns the 500 response code.
· Http _ 503-the server returns the 503 response code.
· Http _ 404-the server returns the 404 response code.
· Off-prohibit requests from being sent to the next FastCGI server.
Note that empty data may have been transferred to the client before the transfer request is sent to the next Server. Therefore, if an error or timeout occurs during data transmission, this command may not fix some transmission errors.

Fastcgi_param

Syntax: fastcgi_param parameter value
Default value: none
Field used: http, server, location
Specify parameters passed to the FastCGI server.
You can use strings, variables, or their combinations. The settings here do not inherit from other fields. The settings in the current field will clear any previous definitions.
Below are the minimum parameters required for a PHP:
Fastcgi_param SCRIPT_FILENAME/home/www/scripts/php $ fastcgi_script_name; fastcgi_param QUERY_STRING $ query_string;
PHP uses the SCRIPT_FILENAME parameter to determine which script to execute. QUERY_STRING contains some parameters in the request.
To process a POST request, you need to add three other parameters:
Fastcgi_param REQUEST_METHOD $ request_method; fastcgi_param CONTENT_TYPE $ content_type; fastcgi_param CONTENT_LENGTH $ content_length;
If PHP has -- enable-force-cgi-redirect during compilation, The REDIRECT_STATUS parameter with a value of 200 must be passed:
Fastcgi_param REDIRECT_STATUS 200;
Fastcgi_pass

Syntax: fastcgi_pass fastcgi-server
Default value: none
Field used: http, server, location
Specify the listening port and address of the FastCGI server, which can be local or other:
Fastcgi_pass localhost: 9000;
Use Unix socket:
Fastcgi_pass unix:/tmp/fastcgi. socket;
You can also use an upstream field name:
Upstream backend {server localhost: 1234;} fastcgi_pass backend;
Fastcgi_pass_header

Syntax: fastcgi_pass_header name
Default value: none
Field used: http, server, location

Fastcgi_read_timeout

Syntax: fastcgi_read_timeout time
Default value: fastcgi_read_timeout 60
Field used: http, server, location
The response timeout time of the front-end FastCGI server. If there are some FastCGI processes that have been output for a long time until they have finished running, or the front-end server response timeout error occurs in the error log, you may need to adjust this value.

Fastcgi_redirect_errors

Syntax: fastcgi_redirect_errors on | off
The command is renamed to fastcgi_intercept_errors.

Fastcgi_send_timeout

Syntax: fastcgi_send_timeout time
Default value: fastcgi_send_timeout 60
Field used: http, server, location
The command sets the time for the upstream server to wait for a FastCGI process to send data. If there are some FastCGI processes that have been output for a long time until they have finished running, you can modify this value, if you find some timeout errors in the error log on the server, you can add this value appropriately.
The timeout time of the request server specified by the command indicates that the two handshakes are completed, instead of the full connection. If no data is transmitted by the client during this period, the server closes the connection.

Fastcgi_split_path_info

Syntax: fastcgi_split_path_info regex
Field used: location
Available version: 0.7.31 or later. Example:
Location ~ ^ (. + \. Php )(. *) $ {... fastcgi_split_path_info ^ (. + \. php )(. *) $; fastcgi_param SCRIPT_FILENAME/path/to/php $ fastcgi_script_name; fastcgi_param PATH_INFO $ response; fastcgi_param PATH_TRANSLATED $ document_root $ fastcgi_path_info ;...}
The SCRIPT_FILENAME parameter for the request "/show. php/article/0001" is set to "/path/to/php/show. php", and The PATH_INFO parameter is "/article/0001 ".

Fastcgi_store

Syntax: fastcgi_store [on | off | path]
Default value: fastcgi_store off
Field used: http, server, location
The path for storing front-end files is specified. The parameter on specifies the path that will use the same root and alias commands. off prohibits storage. In addition, variables can be used in the parameter to make the path clearer:
Fastcgi_store/data/www $ original_uri;
The "Last-Modified" header in the response sets the Last modification time of the file. To make these files more secure, you can save them as temporary files in a directory and use the fastcgi_temp_path command.
This command can be used to create a local copy for backend dynamic output that is not frequently changed. For example:
Location/images/{root/data/www; error_page 404 =/fetch $ uri;} location/fetch {internal; fastcgi_pass fastcgi: // backend; fastcgi_store on; fastcgi_store_access user: rw group: rw all: r; fastcgi_temp_path/data/temp; alias/data/www ;}
Fastcgi_store is not a cache. In some cases, it is more like an image.

Fastcgi_store_access

Syntax: fastcgi_store_access users: permissions [users: permission...]
Default value: fastcgi_store_access user: rw
Field used: http, server, location
This parameter specifies the permission to create a file or directory, for example:
Fastcgi_store_access user: rw group: rw all: r;
If you want to specify the permissions of the person in a group, you can leave the user blank, for example:
Fastcgi_store_access group: rw all: r;
Fastcgi_temp_path

Syntax: fastcgi_temp_path path [level1 [level2 [level3]
Default value: fastcgi_temp_path fastcgi_temp
Field used: http, server, location
The command specifies the path of the temporary data file transmitted from another server. You can also specify the level-3 directory that has been hashed and the level value specifies the number of tags to be hashed. For example, in the following configuration:
Fastcgi_temp_path/spool/nginx/fastcgi_temp 1 2;
Temporary files are similar to the following:
/Spool/nginx/fastcgi_temp/7/45/00000123457
· Parameters transmitted to the FastCGI server

Request headers are transmitted to the FastCGI server as parameters and run on the FastCGI server as specific applications and scripts. These parameters are usually obtained as environment variables. For example, the "User-agent" header is transmitted with the HTTP_USER_AGENT parameter. In addition, some other http headers can be freely transmitted using the fastcgi_param command.

· Variables

$ Fastcgi_script_name

This variable is equal to a request URI ending with a slash plus the parameter specified by fastcgi_index. You can use this variable to replace SCRIPT_FILENAME and PATH_TRANSLATED to determine the php script name.
For example, request "/info /":
Fastcgi_index index. php; fastcgi_param SCRIPT_FILENAME/home/www/scripts/php $ fastcgi_script_name;
SCRIPT_FILENAME is equal to "/home/www/scripts/php/info/index. php ".

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.