Nginx Basic Configuration Detailed description

Source: Internet
Author: User
Tags epoll
1. The advantages and disadvantages of Apache server and Nginx:
We used to use Apache extensively as a httpserver.
Apache has excellent performance, and can provide a variety of features through the module.
1) First Apache response to the client is to support concurrency, after running httpd This daemon process, it will produce multiple child processes/threads at the same time, each child process/thread responds to the client's request separately;
2) In addition, Apache can provide static and dynamic services, for example, the parsing of PHP is not implemented by poor performance CGI, but is implemented by PHP-enabled modules (usually MOD_PHP5, or called APXS2).
3) Disadvantages:
So this server, commonly called Apache, is process-based server, which is a multi-process-based httpserver because it needs to respond to each user request to create a child process/thread;
The disadvantage is that if there is a lot of concurrent requests (which is common in large portal sites), very many threads are required, which consumes a lot of CPU and memory for the system resources. Therefore, concurrency processing is not an Apache strength.
4) Workaround:
At present, there is another kind of webserver, which is more superior in concurrency, called asynchronous servers asynchronous server. The most famous are Nginx and lighttpd. The so-called asynchronous server is the Event-driven of the event driver pattern, except that a user's concurrent requests usually require only a single or several threads. As a result, very few system resources are occupied. These are also known as lightweight Web servers.
For example, for a 10,000 concurrent connection request, Nginx may use only a few m of memory, while Apache may need to use hundreds of m of memory resources.
2. Single use in practice:
1) about the single use of Apache as a httpserver we do not need to do more introduction, very common applications;
Above we introduced to Apache for PHP and other server-side script support is implemented through its own modules, and superior performance.
2) We can also use Nginx or lighttpd as a httpserver.
Nginx and LIGHTTPD and Apache are similar to each other through a variety of modules can be extended to the functionality of the server, the same is done through the Conf configuration file to configure the various options.
For PHP and so on, Nginx and lighttpd do not have built-in modules to support PHP, but through the fastcgi to support.
LIGHTTPD can provide services such as CGI, FastCGI and scgi through modules, LIGHTTPD is capable of automatically spawning FastCGI backends as well as using Exter Nally spawned processes.
Nginx does not provide its own functionality to handle PHP, and requires third-party modules to provide a way to integrate PHP fastcgi.

-------------------------------rewrites all non-http://bbs.it-home.org/access = http://bbs.it-home.org/
server_name web90.***.com;

if ($host = "web90.***.com") {
Rewrite ^ (. *) $ http://bbs.it-home.org/$1 permanent;
}

---------------------------------nginx Stop/Smooth restart #p# pagination title #e#

Nginx's signal control

Term,int Quick Close
QUIT calmly close
HUP smooth Restart, reload configuration file
USR1 re-opening log files for larger use when cutting logs
USR2 Smooth Upgrade Executable program
WINCH gracefully close the work process


1) calmly stop:

Kill-quit Nginx Main process number

Kill-quit '/usr/local/webserver/nginx/logs/nginx.pid '


2) Quick Stop:

Kill-term Nginx Main process number

Kill-term '/usr/local/webserver/nginx/logs/nginx.pid '

KILL-INTN Ginx Main process number

Kill-int '/usr/local/webserver/nginx/logs/nginx.pid '

3) Force stop all Nginx processes

Pkill-9 Nginx


1) Smooth Restart

Kill-hup Nginx Main process number

Kill-hup '/usr/local/webserver/nginx/logs/nginx.pid '

-----------------------------nginx.conf
#p # pagination Title #e#


Worker_processes 8;

Specify number of work-derived processes

Typically equals twice times the total number of cores or total cores of the CPU, such as two quad-core CPUs, with a total of 8 cores
    1. Events
    2. {
    3. Use Epoll; Using the network I/O model, Linux systems recommended EPOLL,FREEBSD recommended Kqueue
    4. Worker_connections 65535; Number of links allowed
    5. }


    6. Location ~. *\. (gif|jpg|jpeg|png|bmp|swf) $ {access_log off; Turn off log expires 30d;//to implement local cache via expires command output header, 30 days} location ~. *\. (JS|CSS) $ {access_log off; close log expires 1h;} ===================== per

    7. {

    8. Access_log off; Log off

    9. Expires 30d;//local cache via expires command output header, 30 days

    10. }

    11. Location ~. *\. (JS|CSS) $

    12. {

    13. Access_log off; Log off

    14. Expires 1h;

    15. }
Copy Code

===================== daily scheduled cut nginx log script

    1. vim/usr/local/webserver/nginx/sbin/cut_nginx_log.sh
    2. #!/bin/bash
    3. # This script run At 00:00

    4. # The Nginx logs path
    5. logs_path= "/usr/local/webserver/nginx/logs/";

    6. mkdir-p ${logs_path}$ (date-d "Yesterday" + "%Y")/$ (date-d "Yesterday" + "%m")/#p # pagination Header #e#
    7. mv ${logs_path}access.log ${logs_path}$ (date-d "Yesterday" + "%Y")/$ (date-d "Yesterday" + "%m")/access_$ (dat E-d "Yesterday" + "%y%m%d"). Log
    8. kill-usr1 ' cat/usr/local/webserver/nginx/nginx.pid '

    9. li>


    10. chown-r www:www cut_nginx_log.sh
    11. chmod +x cut_nginx_log.sh


    12. crontab-e
    13. XX * * */bin/bash/usr/local/webserver/nginx/sbin/cut_nginx_l og.sh


    14. #/sbin/service crond restart
Copy Code--------------nginx Configuring gzip compression

In general, the compressed HTML, CSS, JS, PHP, jhtml and other files, the size can be reduced to the original 25%, that is, the original 100k of HTML, compressed only 25k left. This can undoubtedly save a lot of bandwidth, but also can reduce the load of the server.
Configuring Gzip in Nginx is easier

In general, simply add the following lines of configuration to the HTTP segment of the nginx.conf

Reference
gzip on;
Gzip_min_length 1000;
Gzip_buffers 4 8k;
Gzip_types text/plain application/x-javascript text/css text/html application/xml;

Re-start Nginx
You can use the Web Gzip detection tool to detect if a webpage has gzip enabled
http://gzip.zzbaike.com/

---------------How to redirect Nginx error page

Error_page 404/404.html;

This 404.html guarantee in the Nginx home directory in the HTML directory, if you need to jump to another address after the 404 error, you can directly set the following:


Error_page 404 http://bbs.it-home.org/;


The same way you can define common 403, 500, and other errors. #p # pagination Title #e#


Special note is that the 404.html file page size is more than 512k, otherwise it will be replaced by IE browser error page ie default.

------------------------------Virtual Host Configuration
  1. server {
  2. Listen 80;
  3. server_name localhost;
  4. Access_log/var/log/nginx/localhost.access.log;

  5. Location/{
  6. Root/var/www/nginx-default;
  7. Index index.php index.html index.htm;
  8. }

  9. Location/doc {
  10. Root/usr/share;
  11. AutoIndex on;
  12. Allow 127.0.0.1;
  13. Deny all;
  14. }

  15. location/images {
  16. Root/usr/share;
  17. AutoIndex on;
  18. }
  19. Location ~ \.php$ {
  20. Fastcgi_pass 127.0.0.1:9000;
  21. Fastcgi_index index.php;
  22. Fastcgi_param Script_filename/var/www/nginx-default$fastcgi_script_name;
  23. Include/etc/nginx/fastcgi_params;
  24. }
  25. }


  26. server {
  27. Listen 80;
  28. server_name sdsssdf.localhost.com;
  29. Access_log/var/log/nginx/localhost.access.log;

  30. Location/{
  31. Root/var/www/nginx-default/console;
  32. Index index.php index.html index.htm; } location/doc {root/usr/share; autoindex on; Allow 127.0.0.1, deny all;} location/images {root/usr/share; Autoinde X on; } location ~ \.php$ {fastcgi_pass 127.0.0.1:9000; Fastcgi_index index.p
  33. #p # pagination Title #e#

  34. }

  35. Location/doc {
  36. Root/usr/share;
  37. AutoIndex on;
  38. Allow 127.0.0.1;
  39. Deny all;
  40. }

  41. location/images {
  42. Root/usr/share;
  43. AutoIndex on;
  44. }
  45. Location ~ \.php$ {
  46. Fastcgi_pass 127.0.0.1:9000;
  47. Fastcgi_index index.php;
  48. Fastcgi_param Script_filename/var/www/nginx-default$fastcgi_script_name;
  49. Include/etc/nginx/fastcgi_params;
  50. }
  51. }
Copy Code----------------------Monitoring

Location ~ ^/nginxstatus/{

Stub_status on; #Nginx Status Monitoring Configuration
}



This monitors the operation information of Nginx via http://localhost/NginxStatus/(Last/not):


Active connections:1
Server accepts handled requests
1 5
reading:0 writing:1 waiting:0



The contents of the Nginxstatus display are as follows: #p # page Title #e#

Active connections– the number of active connections currently being processed by Nginx.
Server accepts handled requests-a total of 14,553,819 connections were processed, 14,553,819 handshakes were successfully created (proving that there was no failure in the middle), and a total of 19,239,266 requests were processed (averaging 1 per handshake). 3 data requests).
Reading--The number of Header information that Nginx reads to the client.
Writing--The number of Header information returned to the client by Nginx.
Waiting--when keep-alive is turned on, this value is equal to active-(reading + writing), meaning that Nginx has processed the host connection that is waiting for the next request instruction.


-------------------------------static file Processing

With regular expressions, we can allow Nginx to identify a variety of static files


Location ~ \. (Htm|html|gif|jpg|jpeg|png|bmp|ico|css|js|txt) $ {

root/var/www/nginx-default/html;
Access_log off;
Expires 24h;
}

For example slices, static HTML files, JS script files and CSS style files, and so on, we hope that Nginx directly processing and return to the browser, this can greatly improve the speed of web browsing. So for this type of file we need to specify the path of the file through the root instruction, and because such files are not often modified, the expires instruction is used to control its cache in the browser to reduce unnecessary requests. The expires directive controls the header of "expires" and "Cache-control" in the HTTP response, which is used to control the page cache. You can write Expires using a format such as the following:

Expires 1 January, 1970, 00:00:01 GMT;
Expires 60s;
Expires 30m;
Expires 24h;
Expires 1d;
Expires Max;
Expires off;

This will automatically jump to var/www/nginx-default/html/1.html when you enter http://192.168.200.100/1.html.

For example, all requests under the images path can be written as:

#p # pagination Title #e#

Location ~ ^/images/{
Root/opt/webapp/images;
}


------------------------dynamic page request processing [cluster]

Nginx itself does not support the current popular JSP, ASP, PHP, PERL and other dynamic pages, but it can be sent through the reverse proxy request to the backend server, such as Tomcat, Apache, IIS, etc. to complete the dynamic page request processing. In the previous configuration example, we first defined some static file requests that were processed directly by Nginx, and all other requests were routed to the backend server via the proxy_pass instruction (Tomcat in the example above). The simplest proxy_pass usage is as follows:
Location/{Proxy_pass http://localhost:8080; Proxy_set_header x-real-ip $remote _addr; we are not using the cluster here, but we are sending the request directly to the 8080 end Port Tomcat Service to complete a JSP-like

Proxy_pass http://localhost:8080;
Proxy_set_header X-real-ip $remote _addr;
}





Instead of using the cluster, we sent the request directly to the TOMCAT service running on port 8080 to complete the request processing like JSP and Servlet.

When the amount of page access is very large, often need multiple application servers to jointly assume the dynamic page execution, then we need to use the cluster's architecture. Nginx defines a cluster of servers through the upstream directive, in the first complete example we define a cluster called Tomcats, which includes three servers with a total of 6 Tomcat services. The wording of the Proxy_pass directive became:


# configuration information for all background servers in the cluster
Upstream Tomcats {
Server 192.168.0.11:8080 weight=10;
Server 192.168.0.11:8081 weight=10;
Server 192.168.0.12:8080 weight=10;
Server 192.168.0.12:8081 weight=10;
Server 192.168.0.13:8080 weight=10;
Server 192.168.0.13:8081 weight=10; #p # page Title #e#
}
Location/{
Proxy_pass http://tomcats;# Reverse Proxy
Include proxy.conf;
}

----------------------Stress test

    1. wget http://bbs.it-home.org//soft/linux/webbench/webbench-1.5.tar.gz
    2. Tar zxvf webbench-1.5.tar.gz
    3. CD webbench-1.5
    4. Make && make install

    5. #webbench-C 100-t http://192.168.200.100/info.php

    6. Parameter description:-C for concurrency number,-T for duration (seconds)

    7. root@ubuntu-desktop:/etc/nginx/sites-available# webbench-c 100-t http://192.168.200.100/info.php
    8. Webbench-simple Web Benchmark 1.5
    9. Copyright (c) Radim Kolar 1997-2004, GPL Open Source software.

    10. Benchmarking:get http://192.168.200.100/info.php
    11. Clients, running Sec.

    12. speed=19032 pages/min, 18074373 bytes/sec.
    13. requests:3172 susceed, 0 failed.
Copy Code
-------------------------------PPC provides nginx detailed configuration instructions


  1. #运行用户
  2. User nobody nobody;
  3. #启动进程
  4. Worker_processes 2; #p # page Title #e#
  5. #全局错误日志及PID文件
  6. Error_log Logs/error.log Notice;
  7. PID Logs/nginx.pid;
  8. #工作模式及连接数上限
  9. Events{use Epoll;
  10. Worker_connections 1024;} #设定http服务器, using its reverse proxy function to provide load balancing support


  11. http{#设定mime类型
  12. Include Conf/mime.types;
  13. Default_type Application/octet-stream;
  14. #设定日志格式
  15. Log_format Main ' $remote _addr-$remote _user [$time _local] "" $request "$status $bytes _sent" "$http _referer" "$http _ User_agent "'" $gzip _ratio "';
  16. Log_format Download ' $remote _addr-$remote _user [$time _local] "" $request "$status $bytes _sent" "$http _referer" "$http _user_agent "" "$http _range" "$sent _http_content_range";
  17. #设定请求缓冲
  18. Client_header_buffer_size 1k;
  19. Large_client_header_buffers 4 4k;

  20. #开启gzip模块
  21. gzip on;
  22. Gzip_min_length 1100;

  23. Gzip_buffers 4 8k;
  24. Gzip_types Text/plain;
  25. Output_buffers 1 32k;
  26. Postpone_output 1460;

  27. #设定access Log
  28. Access_log Logs/access.log Main;
  29. Client_header_timeout 3m;
  30. Client_body_timeout 3m;
  31. Send_timeout 3m;
  32. Sendfile on;
  33. Tcp_nopush on;
  34. Tcp_nodelay on;
  35. Keepalive_timeout 65;

  36. #设定负载均衡的服务器列表
  37. Upstream mysvr{#weigth参数表示权值, the higher the weight, the greater the chance of being assigned.
  38. #本机上的Squid开启3128端口 #p# Page Title #e#
  39. Server 192.168.8.1:3128 weight=5;
  40. Server 192.168.8.2:80 weight=1;
  41. Server 192.168.8.3:80 weight=6;
  42. }

  43. #设定虚拟主机
  44. Server{listen 80;
  45. server_name 192.168.8.1 www.okpython.com;
  46. CharSet gb2312;
  47. #设定本虚拟主机的访问日志
  48. Access_log Logs/www.yejr.com.access.log Main;
  49. #如果访问/img/*,/js/*,/css/* Resources, then take the local file directly, not through squid
  50. #如果这些文件较多, this method is not recommended because the cache effect is better through squid
  51. Location ~ ^/(IMG|JS|CSS)/{
  52. root/data3/html;
  53. Expires 24h;
  54. } #对/Enable load Balancer location/{Proxy_pass http://mysvr; proxy_redirect off; Proxy_set_header Host $host; Proxy_set_header x-re Al-ip $remote _addr; Proxy_set_header x-forwarded-for $proxy _add_x_


  55. #对 "/" Enable load balancing
  56. Location/{
  57. Proxy_pass Http://mysvr;
  58. Proxy_redirect off;
  59. Proxy_set_header Host $host;
  60. Proxy_set_header X-real-ip $remote _addr;
  61. Proxy_set_header x-forwarded-for $proxy _add_x_forwarded_for;
  62. Client_max_body_size 10m;
  63. Client_body_buffer_size 128k;
  64. Proxy_connect_timeout, #p # page title #e#
  65. Proxy_send_timeout 90;
  66. Proxy_read_timeout 90;
  67. Proxy_buffer_size 4k;
  68. Proxy_buffers 4 32k;
  69. Proxy_busy_buffers_size 64k;
  70. Proxy_temp_file_write_size 64k;
  71. }
  72. #设定查看Nginx状态的地址
  73. Location/nginxstatus {
  74. Stub_status on;
  75. Access_log on;


  76. Auth_basic "Nginxstatus";
  77. Auth_basic_user_file conf/htpasswd; The contents of the #conf/htpasswd file are generated using the HTPASSWD tools provided by Apache.
  78. }
  79. }
  80. }
Copy Code

  • 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.