Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Detailed introduction of nginx from compilation and installation to configuration file instructions in Chinese

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

This article gives a detailed description of Nginx from compilation and installation to configuration file instructions, each step is described in detail, and can be used as a guide for installing Nginx

All right, don't say much and get to the point.

1. Install nginx

1.1 Select stable version of Nginx

We compiled and installed nginx to customize our module, the machine CentOS 6.2 x86x64. First install the missing dependency package:

# yum-y install gcc gcc-c++ make libtool zlib zlib-devel openssl openssl-devel pcre pcre-devel

If these packages are not available on yum, you can download the source code to compile and install them, just pay attention to the directory where you install them by default, and make sure that you can find these dynamic library files (ldconfig) below when you install nginx.

Download the stable version of nginx-1.6.3.tar.gz from https://www.jb51.net/softs/35633.html and extract it under / usr/local/src.

In order to prepare for the follow-up, we download another 2 plug-in modules:

Nginx_upstream_check_module-0.3.0.tar.gz-check the status of the back-end server

Nginx-goodies-nginx-sticky-module-ng-bd312d586752.tar.gz-- backend does load balancing to solve session sticky problem

It is recommended to rename the directory to nginx-sticky-module-ng-1.2.5 after decompression under / usr/local/src. Additional patches are required for use with upstream_check module. Please refer to nginx load balancer configuration.

Please pay attention to the compatibility between the plug-in and the version of nginx. Generally, the newer the plug-in, the better. Nginx does not need to catch up with the new, and stability comes first.

Nginx-1.4.7,nginx-sticky-module-1.1,nginx_upstream_check_module-0.2.0, there is no problem with this match.

Sticky-1.1 and nginx-1.6 versions failed to keep up with compilation errors due to updates. (you can use Tengine directly, and these modules are included by default)

[root@cachets nginx-1.6.3] # pwd/usr/local/src/nginx-1.6.3 [root@cachets nginx-1.6.3]. / configure-- prefix=/usr/local/nginx-1.6-- with-pcre\ >-- with-http_stub_status_module-- with-http_ssl_module\ >-- with-http_gzip_static_module-- with-http_realip_module\ >-- add-module=../nginx_upstream _ check_module-0.3.0 [root@cachets nginx-1.6.3] # make & & make install

1.2 description of common compilation options for Nginx

Most commonly used modules in nginx are installed by default when compiling. / configure-- help starts with-- without.

-- prefix=PATH: specify the installation directory for nginx. Default / usr/local/nginx

-- conf-path=PATH: sets the path to the nginx.conf configuration file. Nginx allows you to start with different configuration files through the-c option on the command line. Default is prefix/conf/nginx.conf

-- user=name: the user who sets the nginx worker process. You can change the user directive in the nginx.conf configuration file at any time after the installation is complete. The default user name is nobody. -- group=name similar

-- with-pcre: sets the source code path of the PCRE library. If it has been installed by yum, use-- with-pcre to find the library file automatically. When using-- with-pcre=PATH, you need to download and decompress the source code of the pcre library from the PCRE website, and leave the rest to Nginx. / configure and make. Perl regular expressions are used in location instructions and ngx_http_rewrite_module modules.

-- with-zlib=PATH: specify the source code decompression directory for zlib (version 1.1.3-1.2.5). Zlib is required for the network transport compression module ngx_http_gzip_module, which is enabled by default.

-- with-http_ssl_module: use the https protocol module. By default, the module is not built. Only if openssl and openssl-devel are installed

-- with-http_stub_status_module: used to monitor the current status of Nginx

-- with-http_realip_module: this module allows us to change the client IP address value (such as X-Real-IP or X-Forwarded-For) in the client request header, which means that the background server can record the IP address of the original client.

-- add-module=PATH: add a third-party external module, such as nginx-sticky-module-ng or cache module. Recompile every time you add a new module (Tengine does not need to be recompiled when newly added to module)

Another compilation scheme is provided:

. / configure\ >-- prefix=/usr\ >-- sbin-path=/usr/sbin/nginx\ >-- conf-path=/etc/nginx/nginx.conf\ >-- error-log-path=/var/log/nginx/error.log\ >-- http-log-path=/var/log/nginx/access.log\ >-- pid-path=/var/run/nginx/nginx.pid\ >-- lock-path=/var/lock/nginx.lock\ >-- user=nginx\ >-- group=nginx\ >-- with-http_ssl_module\ >-- with-http_stub_status_module\ >-- with-http_gzip_static_module >-- http-client-body-temp-path=/var/tmp/nginx/client/\ >-- http-proxy-temp-path=/var/tmp/nginx/proxy/\ >-- http-fastcgi-temp-path=/var/tmp/nginx/fcgi/\ >-- http-uwsgi-temp-path=/var/tmp/nginx/uwsgi \ >-with-pcre=../pcre-7.8 >-with-zlib=../zlib-1.2.3

1.3 Nginx startup and shutdown

# # check whether the configuration file is correct # / usr/local/nginx-1.6/sbin/nginx-t #. / sbin/nginx-V # you can see the compilation option # # start and close #. / sbin/nginx # default configuration file conf/nginx.conf,-c specifies #. / sbin/nginx-s stop or pkill nginx## restart The configuration file #. / sbin/nginx-s reload or kill-HUP `cat / usr/local/nginx-1.6/logs/ nginx.pid` specified at startup will not be changed.

Of course, you can also manage nginx as a system service, download nginx to / etc/init.d/, to modify the path and then grant executable permissions.

# service nginx {start | stop | status | restart | reload | configtest}

1.4 Nginx yum installation

Yum installing rpm packages is much easier than compiling and installing. Many modules are installed by default, but the disadvantage is that if you want to install third-party modules in the future, there is no way.

# vi / etc/yum.repo.d/nginx.repo [nginx] name=nginx repo baseurl= http://nginx.org/packages/centos/$releasever/$basearch/ gpgcheck=0 enabled=1

The rest can be done with yum install nginx, or you can install a specified version with yum install nginx-1.6.3 (as long as you see the corresponding version in packages, which is the latest stable version by default).

2. Nginx.conf configuration file

The Nginx configuration file is divided into four main parts:

Main (Global Settings)

Server (host settings)

Upstream (upstream server settings, mainly reverse proxy and load balancer related configurations)

Location (setting after URL matches a specific location)

Each part contains several instructions.

The instructions set in the main part will affect the settings of all other parts.

The instructions in the server section are mainly used to specify the virtual host domain name, IP and port.

Upstream instructions are used to set up a series of back-end servers, reverse proxies and load balancing of back-end servers.

The location part is used to match the location of the page (for example, the root directory "/", "/ images", and so on).

The relationship between them: server inherits main,location inherits server

Upstream will neither inherit instructions nor be inherited. It has its own special instructions and does not need to be used elsewhere.

Several instruction contexts currently supported by nginx:

2.1 Nginx Universal configuration

The following nginx.conf simply implements an example of nginx acting as a reverse proxy server at the front end, dealing with static files such as js and png, and forwarding dynamic requests such as jsp to other servers tomcat:

User www www;worker_processes 2 error error log logs/error.log;#error_log logs/error.log notice;#error_log logs/error.log info;pid logs/nginx.pid;events {use epoll; worker_connections 2048;} http {include mime.types; default_type application/octet-stream # log_format main'$remote_addr-$remote_user [$time_local] "$request" #'$status $body_bytes_sent "$http_referer" #'"$http_user_agent"$http_x_forwarded_for"; # access_log logs/access.log main; sendfile on; # tcp_nopush on; keepalive_timeout 65; # gzip compression function sets gzip on; gzip_min_length 1k; gzip_buffers 4 16k Gzip_http_version 1.0; gzip_comp_level 6; gzip_types text/html text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml; gzip_vary on; # http_proxy set client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 75; proxy_send_timeout 75; proxy_read_timeout 75; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k Proxy_temp_file_write_size 64k; proxy_temp_path / usr/local/nginx/proxy_temp 12; # set load balancer backend server list upstream backend {# ip_hash; server 192.168.10.100 usr/local/nginx/proxy_temp 8080 max_fails=2 fail_timeout=30s; server 192.168.10.101 usr/local/nginx/proxy_temp 8080 max_fails=2 fail_timeout=30s;} # very important virtual host configuration server {listen 80 Server_name itoatest.example.com; root / apps/oaapp; charset utf-8; access_log logs/host.access.log main; # pair / all do load balancing + reverse proxy location / {root / apps/oaapp; index index.jsp index.html index.htm; proxy_pass http://backend; proxy_redirect off # backend Web servers can obtain users' real IP proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504 through X-Forwarded-For } # static files, processed by nginx itself, do not go to backend to request tomcat location ~ * / download/ {root / apps/oa/fs;} location ~. *\. (gif | jpg | jpeg | png | png | txt | js | css) ${root / apps/oaapp; expires 7d;} location / nginx_status {stub_status on; access_log off; allow 192.168.10.0x24 Deny all;} location ~ ^ / (WEB-INF) / {deny all;} # error_page 404 / 404.html; # redirect server error pages to the static page / 50x.html # error_page 500502503504 / 50x.hml; location = / 50x.html {root html;} # # other virtual hosts, server instruction starts}

2.2 description of Nginx common instructions

2.2.1 Nginx main global configuration

Some parameters that nginx has nothing to do with specific business functions (such as http service or email service proxy) at run time, such as the number of working processes, the identity of running, and so on.

Woker_processes 2

In the top-level main section of the configuration file, the number of worker processes of the worker role, and the master process receives and assigns requests to worker for processing. This value can be simply set to the number of cores of cpu grep ^ processor / proc/cpuinfo | wc-l, which is also an auto value. If ssl and gzip are enabled, it should be set to the same or even 2 times the number of logical CPU, which can reduce the number of CPU O operations. If the nginx server has other services, you can consider an appropriate reduction.

Worker_cpu_affinity

Is also written in the main section. In the case of high concurrency, the performance loss caused by field reconstruction such as registers caused by multi-CPU core switching can be reduced by setting cpu viscosity. Such as worker_cpu_affinity 0001 0010 0100 1000; (quad core).

Worker_connections 2048

Write it in the events section. The maximum number of connections that each worker process can handle (initiate) concurrently (including all connections to the client or back-end proxied server). Nginx, as a reverse proxy server, calculates the maximum number of connections in the formula = worker_processes * worker_connections/4, so the maximum number of client connections here is 1024. It doesn't matter if it can be increased to 8192, depending on the situation, but cannot exceed the following worker_rlimit_nofile. When nginx is the http server, the formula is divided by 2.

Worker_rlimit_nofile 10240

Write it in the main section. The default is not set, which can be limited to the operating system's maximum limit of 65535.

Use epoll

Write it in the events section. Under the Linux operating system, nginx uses the epoll event model by default. Thanks to this, nginx is quite efficient under the Linux operating system. At the same time, Nginx adopts kqueue, an efficient event model similar to epoll, on OpenBSD or FreeBSD operating systems. Use select only when the operating system does not support these efficient models.

2.2.2 Nginx http server

Some configuration parameters related to providing http services. For example: whether to use keepalive ah, whether to use gzip for compression and so on.

Sendfile on

Turn on the efficient file transfer mode, and the sendfile instruction specifies whether nginx calls the sendfile function to output files, reducing the context switch from user space to kernel space. For ordinary applications, set it to on. If it is used for downloading and other application disk IO heavy-loaded applications, it can be set to off to balance the processing speed of disk and network Imax O and reduce the load of the system.

Keepalive_timeout 65

Long connection timeout in seconds, this parameter is very sensitive, involving the type of browser, back-end server timeout settings, operating system settings, you can start another article. When a persistent connection requests a large number of small files, the overhead of rebuilding the connection can be reduced, but if a large file is uploaded, it will fail if the upload is not completed within 65 seconds. If the setup time is too long and there are many users, keeping the connection for a long time will take up a lot of resources.

Send_timeout

Used to specify the timeout for the response client. This timeout is limited to the time between two connection activities. If the client has no activity beyond this time, Nginx will close the connection.

Client_max_body_size 10m

The maximum number of bytes of a single file that the client is allowed to request. If a large file is uploaded, please set its limit value

Client_body_buffer_size 128k

Maximum number of bytes requested by the buffer proxy buffer client

Module http_proxy

This module implements the function of nginx as a reverse proxy server, including caching (see article)

Proxy_connect_timeout 60

Nginx connection timeout with backend server (proxy connection timeout)

Proxy_read_timeout 60

Timeout between two successful response operations with the back-end server after a successful connection (proxy receive timeout)

Proxy_buffer_size 4k

Set the buffer size of the proxy server (nginx) to read and save account information from the backend realserver. By default, it is the same as the proxy_buffers. In fact, you can set this instruction value a little smaller.

Proxy_buffers 4 32k

Proxy_buffers buffer, nginx caches responses from the back-end realserver for a single connection, if the average page size is less than 32k, set this

Proxy_busy_buffers_size 64k

Buffer size under high load (proxy_buffers*2)

Proxy_max_temp_file_size

When proxy_buffers cannot hold the response content of the back-end server, it will save some of it to the temporary file on the hard disk. This value is used to set the maximum temporary file size. The default is 1024m, which has nothing to do with proxy_cache. Greater than this value, it will be returned from the upstream server. Set to 0 to disable.

Proxy_temp_file_write_size 64k

This option limits the size of the temporary file per write when the server that caches the proxy responds to the temporary file. Proxy_temp_path (at compile time) specifies which directory to write to.

Proxy_pass,proxy_redirect see the location section.

Module http_gzip:

Gzip on: enable gzip to compress output and reduce network transmission.

Gzip_min_length 1k: sets the minimum number of bytes of pages allowed to be compressed. The number of page bytes is obtained from the content-length of the header header. The default value is 20. It is recommended to set the number of bytes greater than 1k. Less than 1k may increase the pressure.

Gzip_buffers 4 16k: set up the system to get several units of cache to store the compressed result data stream of gzip. 4 16k represents 4 times the applied memory in 16k units of the original data size.

Gzip_http_version 1.0: used to identify the version of the http protocol, early browsers do not support Gzip compression, users will see garbled, so in order to support the previous version added this option, if you use the reverse proxy of Nginx and expect to enable Gzip compression, because the end communication is http/1.0, please set it to 1.0.

Gzip_comp_level 6: gzip compression ratio, 1 compression ratio minimum processing speed is the fastest, 9 compression ratio is the largest but processing speed is the slowest (transmission is fast but consumes cpu)

Gzip_types: matches the mime type for compression, and the "text/html" type is always compressed, whether specified or not.

Gzip_proxied any: when Nginx is enabled as a reverse proxy, it determines whether the results returned by the backend server are compressed or not. The prerequisite for matching is that the backend server must return a header header containing "Via".

Gzip_vary on: related to the http header, a Vary: Accept-Encoding is added to the response header, which allows the front-end cache server to cache gzip-compressed pages, for example, Nginx-compressed data with Squid.

2.2.3 Nginx server virtual host

Several virtual hosts are supported on the http service. Each virtual host has a corresponding server configuration item, which contains the configuration related to the virtual host. Several server can also be established when providing proxies for mail services. Each server is distinguished by listening for addresses or ports.

Listen

The listening port is 80 by default, and those less than 1024 should be started with root. It can be in the form of listen *: 80, listen 127.0.0.1 and so on.

Server_name

Server names, such as localhost, www.example.com, can be matched by regular matching.

Module http_stream

This module uses a simple scheduling algorithm to achieve load balancing from the client IP to the back-end server. The upstream is followed by the name of the load balancer, and the back-end realserver is organized in {} by host:port options;. If only one backend is proxied, it can also be written directly in proxy_pass.

2.2.4 Nginx location

In a http service, a series of configuration items corresponding to certain URL.

Root / var/www/html

Define the default site root location for the server. If locationURL matches a subdirectory or file, root is useless and is usually placed inside or / under the server instruction.

Index index.jsp index.html index.htm

Define the file name accessed by default under the path, which is usually followed by root

Proxy_pass http:/backend

The request goes to the list of servers defined by backend, that is, the reverse proxy, which corresponds to the upstream load balancer. You can also proxy_pass http://ip:port.

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

These four are set up like this for the time being. if you delve into them, each of them involves very complex content and will be interpreted through another article.

With regard to the writing of location matching rules, it can be said that it is particularly critical and basic. Refer to the article nginx configuration location summary and rewrite rule writing.

2.3 other

2.3.1 access Control allow/deny

The access control module of Nginx is installed by default, and it is very simple to write. It can have multiple allow,deny, allow or prohibit access to a certain ip or ip segment, and stop matching if any rule is satisfied in turn. Such as:

Location / nginx-status {stub_status on; access_log off;# auth_basic "NginxStatus"; # auth_basic_user_file / usr/local/nginx-1.6/htpasswd; allow 192.168.10.100; allow 172.29.73.0 Compact 24; deny all;}

We also use the htpasswd of the httpd-devel tool to set the login password for the access path:

# htpasswd-c htpasswd adminNew passwd:Re-type new password:Adding password for user admin# htpasswd htpasswd admin / / modify admin password # htpasswd htpasswd sean / / add one more authenticated user

This generates a password file that is encrypted using CRYPT by default. Open the comments on the above two lines of nginx-status, and restart nginx takes effect.

2.3.2 Nginx lists directories autoindex

Nginx does not allow entire directories to be listed by default. If you need this feature, open the nginx.conf file and add the other two parameters of autoindex on;, to the location,server or http section.

Autoindex_exact_size off

The default is on, which shows the exact size of the file, in bytes. After changing to off, the approximate size of the file is displayed, in kB or MB or GB

Autoindex_localtime on

The default is off, and the file time displayed is GMT time. When changed to on, the file time displayed is the server time of the file

Location / images {root / var/www/nginx-default/images; autoindex on; autoindex_exact_size off; autoindex_localtime on;}

The above is the text of the detailed description of nginx from compilation and installation to configuration file. I hope it will be helpful to you. In the relevant articles below, there are more excellent articles about Nginx compilation, installation and configuration that you can continue to read.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report