Home  >  Article  >  Backend Development  >  Nginx Common Application Technology Guide [Nginx Tips] Second Edition

Nginx Common Application Technology Guide [Nginx Tips] Second Edition

WBOY
WBOYOriginal
2016-07-30 13:29:321308browse
Author: NetSeek http://www.linuxtone.org (IT Operation and Maintenance Expert Network | Cluster Architecture | Performance Tuning)
Welcome to reprint. When reprinting, please be sure to indicate the original source and author information of the article in the form of a hyperlink and this statement.
First published: 2008-11-25 Updated: 2009-1-14
Table of contents
1. Basic knowledge of Nginx
2. Nginx installation and debugging
Three, Nginx Rewrite
Four, Nginx Redirect
Five, Nginx directory automatically adds slashes:
Six, Nginx Location
7. Nginx expires
8 Nginx Cache
Twelve,
Nginx Load balancing
Thirteen, Nginx Simple Optimization
                                                                                  ’ ’s ’ s ’ s ’ ’ ’ ’ ’ ’ ’ ’ ’ ’ ’ ’ Problem and error handling.
17. Download related resources [Foreword]: This technical guide is written to popularize the use of NGINX in China, and to more conveniently help everyone understand and master some of the usage skills of NGINX. Many of the tips in this guide come from the Internet, at work, or from questions asked by friends on the Internet. I would like to express my gratitude and respect to friends on the Internet who are willing to share! Welcome everyone to join me in enriching this technical guide and making better suggestions! Friends, please pay attention to: http://www.linuxtone.org technology sharing community! Let’s learn from each other and make progress together!
1. Basic knowledge of Nginx 1. Introduction
Nginx ("engine x") is a high-performance HTTP and reverse proxy server, as well as an IMAP/POP3/SMTP proxy server. Nginx was developed by Igor Sysoev for Russia's second most visited Rambler.ru site, where it has been running for more than two and a half years. Igor releases the source code under a BSD-like license. Although it is still a beta version, Nginx Already known for its stability, rich feature set, sample configuration files, and low system resource consumption.
For more information, please see the official wiki: http://wiki.codemongers.com/2. Advantages of Nginx
nginx, as an HTTP server, has the following basic features: 1) Process static files, index files and automatic indexing; open file descriptor buffering.
2) Cache-free reverse proxy acceleration, simple load balancing and fault tolerance.
3) FastCGI, simple load balancing and fault tolerance.
4) Modular structure. Including filters such as gzipping, byte ranges, chunked responses, and SSI-filter. If multiple SSIs present in a single page are processed by FastCGI or another proxy server, this processing can run in parallel without waiting for each other.
5) Support SSL and TLS SNI
.
Nginx is specially developed for performance optimization. Performance is its most important consideration, and implementation pays great attention to efficiency. It supports the kernel Poll model and can withstand high loads. Reports indicate that it can support up to 50,000 concurrent connections.
Nginx has high stability. When other HTTP servers encounter access peaks, or someone maliciously initiates a slow connection, it is also likely to cause the server's physical memory to be exhausted, frequent swapping, and loss of response, and the server can only be restarted. For example, once apache currently has more than 200 processes, the web response speed will be obviously very slow. Nginx adopts phased resource allocation technology, making its CPU and memory usage very low. nginx officially states that it maintains 10,000 inactive connections. It only occupies 2.5M of memory, so attacks like DOS are basically harmful to nginx. is useless. In terms of stability, nginx is better than lighthttpd.
Nginx supports hot deployment.It is particularly easy to start and can run almost 24/7 without any need to restart even if it runs for several months. You can also upgrade the software version without interrupting service.
Nginx adopts the master-slave model, which can fully utilize the advantages of SMP and reduce the blocking delay of worker processes in disk I/O. When using select()/poll() calls, you can also limit the number of connections per process.
Nginx code quality is very high, the code is very standardized, the techniques are mature, and the module expansion is also easy. Particularly worth mentioning are the powerful Upstream and Filter chains. Upstream lays a good foundation for writing modules such as reverse proxy and communication with other servers. The coolest part of the Filter chain is that each filter does not have to wait for the previous filter to complete execution. It can use the output of the previous filter as the input of the current filter, which is a bit like the Unix pipeline. This means that a module can start compressing requests sent from the backend server, and the module can The compressed stream is forwarded to the client before completing the entire request to the backend server.
Nginx adopts some of the latest features provided by os such as support for sendfile (Linux 2.2+), accept-filter (FreeBSD 4.1+), TCP_DEFER_ACCEPT (Linux 2.4+), thus greatly improving performance
2. Nginx Installation and debugging
1. Pcre installation

CODE:

./configure<br> make && make install<br> cd ../2. nginx compile and install

CODE:

./configure --user=www --group=www --prefix=/usr/local/nginx/ --with-http_stub_status_module --with-openssl=/usr/local/openssl <br>make && make installFor more detailed module customization and installation, please refer to the official wiki.
3. Nginx configuration file test:

CODE:

# /usr/local/nginx/sbin/nginx -t //Debug The key commands of the configuration file need to be mastered.<br>2008/12/16 09:08:35 [info] 28412#0: the configuration file / usr/local/nginx/conf/nginx.conf syntax is ok <br>2008/12/16 09:08:35 [info] 28412#0: the configuration file /usr/local/nginx/conf/nginx.conf was tested successfully 3. Nginx startup:

CODE:

# /usr/local/nginx/sbin/nginx4. Nginx Configuration file modification and reloading:

CODE:

# kill -HUP `cat /usr/local/nginx/logs/nginx.pid`
3. Nginx Rewrite
1. Nginx Rewrite basic mark ( flags)
last - This Flag is basically used.
※Equivalent to the [L] mark in Apache, indicating that rewrite is completed and subsequent rules will no longer be matched
break - Abort Rewirte and no longer match
redirect - Return to temporary reset Directed HTTP status 302
permanent - Returns permanent redirected HTTP status 301
※The original url supports regular expressions The rewritten url does not support regular expressions
2. Regular expression matching, Among them:
  * ~                                                                                     can be case-sensitive matching
       *         * ~ *           can can be matched in case-insensitive
        * !~ and !~* can be case-sensitive mismatch and case-insensitive mismatch respectively
3. File and directory matching, among which:
* -f and !-f are used to determine whether the file exists
* -d and !-d are used to determine whether the directory exists
* -e and !-e are used to determine whether a file or directory exists
* -x and !-x are used to determine whether a file is executable
3. Some of the available global variables of Nginx can be used for conditional judgment:

CODE :

$args<br>$content_length<br>$content_type<br>$document_root<br>$document_uri<br>$host<br>$http_user_agent<br>$http_cookie<br>$limit_rate<br>$request_body_file<br>$request_method<br>$remote_addr<br>$remote_ port<br>$remote_user<br>$request_filename<br>$request_uri <br>$query_string<br>$scheme<br>$server_protocol<br>$server_addr<br>$server_name<br>$server_port<br>$uri4. Nginx Redirect
Redirect all linuxtone.org and netseek.linuxtone.org domain names to http: //www.linuxtone.org

CODE:

server<br>{<br>listen 80;<br>server_name linuxtone.org netseek.linuxtone.org;<br>index index.html index.php;<br>root /data/www/wwwroot;<br>if ($host !~ "^ www.linxtone.org$") {<br>rewrite ^(.*) http://www.linuxtone.org$1 redirect;<br>}<br>........................ .....<br>}5. Nginx directory automatically adds slash:

CODE:

$IF (-d $ Request_filename) { REWRITE ^/(.*) ([ ^/]) $ Http: // $ Host/$ 1 $ 2/Permanent; Basic syntax: [Basically consistent with the rewrite regular matching syntax above] <br><br>location [=|~|~*|^~] /uri/ { … }
                                                                                                                                          * ~* is case-insensitive matching

* !~ and !~* are case-sensitive mismatch and case-insensitive mismatch respectivelyExample 1:
location = / {# matches the query / only.
# matches the query / only.
}
matches any query because all requests start with /. But regular expression rules and long block rules will be prioritized and matched against queries
Example 2:
location ^~ /images/ {
# matches any query beginning with /images/ and halts searching,
# so regular expressions will not be checked.
# Matches any query that starts with /images/ and stops the search. Any regular expression will not be tested.
Example 3:
location ~* .(gif|jpg|jpeg)$ {

# matches any request ending in gif, jpg, or jpeg. However, all
# requests to the /images/ directory will be handled by
}
# Matches any request ending in gif, jpg or jpeg.
7. Nginx expires1. Expires according to file type
CODE:# Add expires header for static contentlocation ~* .(js|css|jpg|jpeg|gif|png|swf)$ {
if (-f $request_filename) { root /data/www/wwwroot/bbs; expires 1d;
break; }}
2. Judge a directory based on

CODE:

# serve static files<br>location ~ ^/(images|javascript|js |css|flash|media|static)/ {<br>root /data/www/wwwroot/down;<br> expires 30d;<br>}<br><br>Eight. Nginx anti-hotlink<br>1. For different file types

CODE:

#Preventing hot linking of images and other files Types<br>location ~ * ^.+. (GIF | JPG | PNG | SWF | FLV | RAR | ZIP) $ {<br> Valid_referrs None Blocked Server_names * .linuxtone.org LinuxTP: // LOCALHO stbaidu.com; <br>if ($invalid_referer) {<br> rewrite ^/ ; # return 403; }}
2. For different directories

CODE:

location /img/ {<br> root /data /www/wwwroot/bbs/img /; A Valid_referrs None Blocked Server_names *.linuxTone.org http: // localhost Baidu.com; <br> ($ invalid_referr) {<br> REWRITE^/; <br> #RETURN 403; <br><br>} <br>} .3. and expires methodsCODE:

#Preventing hot linking of images and other files types

location ~* ^.+.(gif|jpg|png|swf|flv|rar|zip)$ {      valid_referers none blocked server_names *.linuxtone.org linuxtone.org http://localhost;<br>if ($invalid_referer } x Access control<br><br><br>1. Nginx ID verification<br> <br>CODE:<br><code>#cd /usr/local/nginx/conf<br>#mkdir htpasswd<br>/usr/local/apache2/bin/htpasswd -c /usr/local/nginx/conf/htpasswd/tongji linuxtone <br>#Add username linuxtone<br>New password: (Enter your password here)<br>Re-type new password: (Enter your password again)<br>Adding password for user<br>http://count.linuxtone.org/tongji/data/index.html (The directory exists /data/www/wwwroot/tongji/data/ directory) <br>Put the following configuration into the virtual host directory. When accessing http://count.linuxtone/tongji/, you will be prompted for password verification: <br>location ~ ^/(tongji) / {<br>                                                                                                                                              auth_basic_user_file /usr/local/nginx/conf/htpasswd/tongji;<br>               }<br><br>2.             Nginx prohibits access to certain types of files File.For example, access to *.txt files is prohibited under Nginx. The configuration method is as follows.
CODE:

location ~* .(txt|doc)$ {

if (-f $request_filename) { root /data /www/wwwroot/linuxtone/test;<br> #rewrite …..can redirect to a URL<br> break;<br> }<br>}<br><br>Method 2:CODE:

location ~* .(txt|doc)$ {

                                                                                                                                                                                              Deny all; deny all; } <br><br>3. Use ngx_http_access_module to restrict ip access<br>CODE:location / {
deny 192.168.1.1; allow 192.168.1.0/24; allow 10.1.1.0/16;

deny all;

} 见 For details, see wiki: Http://wiki.CodeMongers.com/nginxhttpaccessModule#allow<br><br>4. Nginx download restrictions and rate Code:

limit_zone Linuxone $ binary_aremote_addr 10M;

Seerver; { Listen 80 : location }<br>..........<br> }<br><br>Only one thread is allowed in the guest room, each thread is 20k.<br>【Note】
limit_zone linuxtone $binary_remote_addr 10m; This can be defined in the main file size limit

6. , The specific size can be adjusted according to your own business.

<br>client_max_body_size 10m; <br><br><br>10. Nginx log processing<br><br><br>1.Nginx log cutting<br><br><br>#contab -e<br><br><br>59 23 * * * /usr/local/sbin/logcron.sh /dev/null 2>&1 [root@count ~]# cat /usr/local/sbin/logcron.sh
CODE:#!/bin/bash<br>log_dir="/data/logs"<br>time=`date +%Y%m%d` <br>/bin/mv ${log_dir}/access_linuxtone.org.log ${log_dir}/access_count .linuxtone.org.$time.log<br>kill -USR1 `cat /var/run/nginx.pid`For more log analysis and processing, please pay attention (you are also welcome to participate in the discussion):http://bbs. linuxtone.org/forum-8-1.html
2. Use AWSTATS to analyze NGINX logs
Set up the Nginx log format and then use awstats for analysis.
Please refer to: http://bbs.linuxtone .org/Thread-56-1-1.html
3. Nginx does not record some logs
There are too many logs, several G, less records per day, the following configuration can be written in the server {} paragraph
location ~ .*.(js|jpg|JPG|jpeg|JPEG|css|bmp|gif|GIF)$
{
access_log off;
}
Eleven, Nginx Cache service configuration
If you need to cache files locally, you need to add the following sub-parameters:

CODE:

proxy_store on;<br>proxy_store_access user:rw group:rw all:rw;<br>proxy_temp_path cache directory; Among them,
proxy_store on is used to enable the cache to local function,
proxy_temp_path is used to specify which directory to cache, such as: proxy_temp_path html;
After the previous step of configuration, although the file is cached locally on the disk, but each request will still pull files to the remote end. In order to avoid pulling files from the remote end, you must modify

CODE:

proxy_pass: <br>if ( !-e $request_filename) {<br> proxy_pass http:/ /mysvr;<br>} is changed to execute proxy_pass conditionally. This condition is that when the requested file does not exist in the directory specified by the local proxy_temp_path, it will be pulled from the backend.

For more advanced applications, you can study ncache. For details, please refer to the ncache-related posts in http://bbs.linuxtone.org.
12. Nginx load balancing
1 . Basic knowledge of Nginx load balancing
nginx upstream currently supports 4 methods of allocation
1), polling (default)
Each request is allocated to a different backend server one by one in chronological order. If If the end server is down, it can be automatically eliminated.
2), weight
specifies the polling probability, weight is proportional to the access ratio, and is used when the back-end server performance is uneven.
2), ip_hash
Each request is allocated according to the hash result of the accessed IP, so that each visitor has fixed access to a back-end server, which can solve the session problem.
3), fair (third party)
allocates requests according to the response time of the back-end server, and priority is given to those with short response times.
4), url_hash (third party)
2. Nginx load balancing instance 1

CODE:

upstream bbs.linuxtone.org {#Define the IP and device status of the load balancing device<br> server 127.0.0.1: 9090 down;<br> server 127.0.0.1:8080 weight=2;<br> server 127.0.0.1:6060;<br> server 127.0.0.1:7070 backup;<br>}Add
proxy_pass in the server that needs to use load balancing http : //bbs.linuxtone.org/ ;
The status of each device is set to:
a) DOWN indicates that the server in front of the single is temporarily not involved in the load
) , the greater the weight of the load.
c) max_fails: The number of allowed request failures is 1 by default. When the maximum number is exceeded, the error defined by the proxy_next_upstream module is returned.
d) fail_timeout: The pause time after max_fails failures.
e) Backup: When all other non-backup machines are down or busy, request the backup machine. So this machine will have the least pressure.
nginx supports setting up multiple groups of load balancing at the same time for use by unused servers.
client_body_in_file_only Set to On, you can record the data from the client post to a file for debugging
client_body_temp_path Set the directory of the recording file to set up to 3 levels of directories
location to match the URL. You can redirect Or perform a new proxy load balancing
3. Nginx load balancing instance 2
distributes requests according to the hash result of the access URL, so that each URL is directed to the same back-end server. It is more effective when the back-end server is cached , can also be used to improve Squid cache hit rate.
Simple load balancing example:
#vi nginx.conf //nginx main configuration file core configuration

CODE:

……….<br>#loadblance my.linuxtone.org<br>       upstream  my.linuxtone.org  {<br>       ip_hash;<br>       server   127.0.0.1:8080;<br>       server   192.168.169.136:8080;<br>       server   219.101.75.138:8080;<br>       server   192.168.169.117;<br>       server   192.168.169.118;<br>       server   192.168.169.119;<br>     }<br>…………..<br>include          vhosts/linuxtone_lb.conf;<br>………<br># vi proxy.conf<br>proxy_redirect off;<br>proxy_set_header Host $host;<br>proxy_set_header X-Real-IP $remote_addr;<br>proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>client_max_body_size 50m;<br>client_body_buffer_size 256k;<br>proxy_connect_timeout 30;<br>proxy_send_timeout 30;<br>proxy_read_timeout 60;<br>proxy_buffer_size 4k;<br>proxy_buffers 4 32k;<br>proxy_busy_buffers_size 64k;<br>proxy_temp_file_write_size 64k;<br>proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;<br>proxy_max_temp_file_size 128m;<br>proxy_store on;<br>proxy_store_access   user:rw  group:rw  all:r;<br>#nginx cache               <br>#client_body_temp_path  /data/nginx_cache/client_body 1 2;<br>proxy_temp_path /data/nginx_cache/proxy_temp 1 2;#vi  linuxtone_lb.conf

CODE:

server<br>    {<br>        listen  80;<br>        server_name my.linuxtone.org;<br>        index index.php;<br>        root /data/www/wwwroot/mylinuxtone;<br>        if (-f $request_filename) {<br>            break;<br>           }<br>        if (-f $request_filename/index.php) {<br>          rewrite (.*) $1/index.php break;<br>        }<br>        error_page 403 http://my.linuxtone.org/member.php?m=user&a=login;<br>        location / {<br>           if ( !-e $request_filename) {<br>               proxy_pass http://my.linuxtone.org;<br>               break;<br>           }<br>           include /usr/local/nginx/conf/proxy.conf;<br>        }<br>}
十三、Nginx简单优化

1.        减小nginx编译后的文件大小 (Reduce file size of nginx)
默认的nginx编译选项里居然是用debug模式(-g)的(debug模式会插入很多跟踪和ASSERT之类),编译以后一个nginx有好几兆。去掉nginx的debug模式编译,编译以后只有几百K
在 auto/cc/gcc,最后几行有:
# debug

CODE:

CFLAGS=”$CFLAGS -g”注释掉或删掉这几行,重新编译即可。
2.        修改Nginx的header伪装服务器
1)        修改nginx.h

CODE:

#vi nginx-0.7.30/src/core/nginx.h<br>#define NGINX_VERSION      "1.8"<br>#define NGINX_VER          "LTWS/" NGINX_VERSION<br>#define NGINX_VAR          "NGINX"<br>#define NGX_OLDPID_EXT     ".oldbin"2) 修改nginx_http_header_filter_module
#vi nginx-0.7.30/src/http/ngx_http_header_filter_module.c
将如下

CODE:

static char ngx_http_server_string[] = "Server: nginx" CRLF;修改为

CODE:

static char ngx_http_server_string[] = "Server: LTWS" CRLF;a)        修改nginx_http_header_filter_module
#vi nginx-0.7.30/src/http/ngx_http_special_response.c
将如下:

CODE:

static u_char ngx_http_error_full_tail[] =<br>"
" NGINX_VER "
" CRLF
" " CRLF
"" CRLF
;

CODE:

static u_char ngx_http_error_tail[] =<br>"
nginx
" CRLF
"" CRLF
"" CRLF
;修改为:

CODE:

static u_char ngx_http_error_full_tail[] =<br>"
"NGINX_VER"
" CRLF
"
http://www.linuxtone.org
" CRLF
"" CRLF
"" CRLF
;
static u_char ngx_http_error_tail[] =<br>"
LTWS
" CRLF
"" CRLF
"" CRLF
;Recompile the environment after modification, and the rendering will be displayed when
404 error occurs (if no error page is specified):


404. png


Use the curl command to view the server header


curl.png


3. Specify the CPU type compilation optimization for a specific CPU.
The default GCC compilation parameter used by nginx is -O
Required For more optimization, you can use the following two parameters
--with-cc-opt='-O3'
--with-cpu-opt=opteron
to make the compilation target a specific CPU and increase the optimization of GCC.
This method only improves performance and does not have a big performance improvement, for your reference.
CPUD type determination: # cat /proc/cpuinfo | grep "model name"
Compilation optimization parameters Reference: http://en.gentoo-wiki.com/wiki/Safe_Cflags
4.Tcmalloc optimizes Nginx performance

CODE:

# wget http://download.savannah.gnu.org/releases/libunwind/ libunwind-0.99-alpha.tar.gz<br># tar zxvf libunwind-0.99-alpha.tar.gz<br># cd libunwind-0.99-alpha/<br># CFLAGS=-fPIC ./configure<br># make CFLAGS=-fPIC<br># make CFLAGS=-fPIC install<br># wget http://google-perftools.googlecode.com/files/google-perftools-0.98.tar.gz<br># tar zxvf google-perftools-0.98.tar.gz<br># cd google-perftools -0.98/<br># ./configure<br># make && make install<br># echo "/usr/local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf<br># ldconfig<br># lsof -n | grep tcmallocCompile nginx Load google_perftools_module:
./configure --with-google_perftools_module
Add nginx.conf to the main configuration file Add:
google_perftools_profiles /path/to/profile;
5. Kernel Parameter optimization
# vi /etc/sysctl.conf #Add the following content at the end:

CODE:

net.ipv4.tcp_fin_timeout = 30 <br>net.ipv4.tcp_keepalive_time = 300 <br>net.ipv4.tcp_syncookies = 1 <br>net.ipv4.tcp_tw_reuse = 1 <br>net.ipv4.tcp_tw_recycle = 1<br>net.ipv4.ip_ local_port_range = 5000 65000 #Make the configuration take effect immediately
/sbin/sysctl -p
14. How to build a high-performance LEMP
Please see: http://www.linuxtone.org/lemp/lemp.pdf
1. Provide complete configuration script download: http://www.linuxtone.org/lemp/scripts.tar.gz
2. Provide NGINX common configuration examples including (virtual host, anti-leeching, Rewrite, access control, Load balancing
Discuz related programs are static and etc.), you can apply it online with only slight modifications. 3. Replace the original xcache with EA and provide relevant simple tuning scripts and configuration files.
For more and updated information, please follow: http://www.linuxtone.org
15. Nginx monitoring
1. RRDTOOL+Perl script drawing monitoring
First install rrdtool, about rrdtool This article does not introduce it. For specific installation, please refer to the linuxtone monitoring section.
#cd /usr/local/sbnin
#wget http://blog.kovyrin.net/files/mrtg/rrd_nginx.pl.txt
#mv rrd_nginx.pl.txt rrd_nginx.pl
#chmod a+x rrd_nginx.pl
#vi rrd_nginx.pl //Set the path to the configuration script file
#!/usr/bin/perl
use RRDs;
use LWP::UserAgent;
# define location of rrdtool databases
my $rrd = '/data/www/wwwroot/nginx/rrd';
# define location of images
my $img = '/data/www/wwwroot/nginx/html';
# define your nginx stats URL
my $URL = "http://219.232.244.13/nginx_status";
…………
【Note】Modify the corresponding path according to your specific situation.
#crontab –e //Add the following
* * * * * /usr/local/sbin/rrd_nginx.pl
After restarting crond, configure the nginx virtual host to point to the /data/www/wwwroot/nginx/html directory, and automatically execute the perl script through crond to generate many pictures.
http://xxx/connections-day. png to see the server status diagram.
2. Official Nginx-rrd monitoring service (multiple virtual hosts) (recommended)
Website: http://www.nginx.eu/nginx-rrd.html
This solution is actually based on the above monitoring An improvement and enhancement of the solution, also install the drawing tool rrdtool and the corresponding perl module first, and then do the following operations:
# yum install perl-HTML*
First create the generated inventory and image storage directory

CODE:

#mkdir -p /data/www/wwwroot/nginx/{rrd,html}<br>#cd /usr/local/sbin<br>#wget http://www.nginx.eu/nginx-rrd/nginx- rrd-0.1.4.tgz<br>#tar zxvf nginx-rrd-0.1.4.tgz<br>#cd nginx-rrd-0.1.4<br>#cd etc/<br>#cp nginx-rrd.conf /etc<br>#cd etc/ cron.d<br>#cp nginx-rrd.cron /etc/cron.d<br>#cd /usr/local/src/nginx-rrd-0.1.4/html<br># cp index.php /data/www/wwwroot/nginx /html/<br>#cd /usr/local/src/nginx-rrd-0.1.4/usr/sbin<br>#cp * /usr/sbin/#vi /etc/nginx-rrd.conf

CODE:

############################################## ####<br>#<br># dir where rrd databases are stored<br>RRD_DIR="/data/www/wwwroot/nginx/nginx";<br># dir where png images are presented<br>WWW_DIR="/data/www/wwwroot/nginx /html";<br># process nice level<br>NICE_LEVEL="-19";<br># bin dir<br>BIN_DIR="/usr/sbin";<br># servers to test<br># server_utl;server_name<br>SERVERS_URL="http://219.32 .205.13/nginx_status;219.32.205.13 http://www.linuxtone.org/nginx_status;www.linuxtone.org""//Adjust according to your specific situation.
SEVERS_URL format http://domain1/ nginx_status;domain1 http://domain2/nginx_status;domain2
This format monitors the connection status of multiple virtual hosts:
Focus on starting the crond service, and then use http://219.32.205.13/nginx/html/ can be accessed. The configuration process is simple!
3. CACTI template monitors Nginx
Use Nginx_status status to draw pictures to implement CACTI monitoring
nginx allows http_stub_status_module when compiling
# vi /usr/local/nginx/conf/nginx.conf

CODE:

location /nginx_status {<br>stub_status on;<br>access_log off;<br>allow 192.168.1.37;<br>deny all;<br>}

CODE:

# kill -HUP `cat /usr/local/nginx/logs/nginx.pid` <br># wget http://forums.cacti.net/download.php?id=12676<br># tar xvfz cacti-nginx.tar.gz<br># cp cacti-nginx/get_nginx_socket_status.pl /data/cacti/scripts/<br># cp cacti-nginx/get_nginx_clients_status.pl /data/cacti/scripts/<br># chmod 755 /data/cacti/scripts/get_nginx*Detection plug-in

CODE:

# /data/cacti/scripts/get_nginx_clients_status.pl http://192.168.1.37/nginx_statusImport in the cacti management panel
cacti_graph_template_nginx_clients_stat.xml
cacti_graph_template_nginx_sockets_stat.xml
16. Frequently Asked Questions and Error Handling
1. Reasons for 400 bad request error And the solution
Configure nginx.conf related settings as follows.
client_header_buffer_size 16k;
large_client_header_buffers 4 64k;
Adjust according to the specific situation, generally just adjust the value appropriately.
2, Nginx 502 Bad Gateway error
proxy_next_upstream error timeout invalid_header http_500 http_503;
Or try setting:
large_client_header_buffers 4 32k;
3. 413 Request Entity Too Large error in Nginx
This error usually occurs when uploading files.
Edit the Nginx main configuration file Nginx.conf, find the http{} section, add
client_max_body_size 10m; //Adjust the size according to your needs.
If you are running php, the size client_max_body_size should be consistent with or slightly larger than the maximum value of the following values ​​in php.ini, so that there will be no errors due to inconsistent sizes of submitted data.
post_max_size = 10M
upload_max_filesize = 2M
4. Solve 504 Gateway Time-out (nginx)
I encountered this problem when upgrading the discuz forum
Generally speaking, This situation may be caused by the nginx default fastcgi process response buffer being too small, which will cause the fastcgi process to be suspended. If your fastcgi service does not handle this suspension well, then it is very likely to cause 504 Gateway Time-out
Nowadays websites, especially some forums, have a lot of replies and a lot of content, and a page can even have hundreds of KB.
The default fastcgi process response buffer is 8K, we can set it larger
In nginx.conf, add: fastcgi_buffers 8 128k
This means setting the fastcgi buffer to 8×128k
Of course If you are performing an immediate operation, you may need to increase the timeout parameter of nginx, for example, set it to 60 seconds: send_timeout 60;
I just adjusted these two parameters, and the result is that the timeout is no longer displayed. OK It is said that the effect is good, but it may also be due to other reasons. There is not much information about nginx at present. Many things require long-term accumulation of experience to achieve results. I look forward to your discovery!
5. How to use Nginx Proxy
A friend’s server runs tomcat on port 8080, IP: 192.168.1.2:8080, and the other machine’s IP: 192.168.1.8. My friend wants to access the tomcat service by visiting http://192.168.1.8. The configuration is as follows :
Configure the nginx.conf of 192.168.1.8 as follows:

CODE:

server {<br>listen 80;<br>server_name java.linuxtone.org<br>location / {<br>proxy_pass http://192.168.1.2:8080 ;<br>include /usr/local/nginx/conf/proxy.conf;<br>}<br>}6. How to close Nginx’s LOG
access_log /dev/null; error_log /dev/null;
Seventeen, Related resource download
1.nginx configuration example and script download:
# wget http://www.linuxtone.org/lemp/scripts.tar.gz #This script example is updated regularly.
【 Attachment]:
This document is updated regularly, and friends are welcome to provide valuable comments to enrich the content of nginx tips.
The latest document is released. Please pay attention to: http://bbs.linuxtone.org

The above introduces the second edition of Nginx Common Application Technology Guide [Nginx Tips], which includes various aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn