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

Example Analysis of Nginx Server Construction and basic configuration

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

Share

Shulou(Shulou.com)05/31 Report--

Today, I would like to share with you the relevant knowledge points of Nginx server building and basic configuration example analysis. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.

Nginx (engine x) is a high-performance http server and reverse proxy server. This software is developed to solve the c10k problem.

The architecture of nginx takes advantage of many features of modern operating systems to implement a high-performance http server. For example, on linux systems, nginx uses mechanisms such as epoll,sendfile,file aio,directio, which makes nginx not only efficient, but also very low resource utilization. It is officially claimed that nginx needs only 2.5m memory to maintain 10000 inactive http keep-alive connections.

Nginx runs multiple processes as needed: a main process (master) and several worker processes (worker). When caching is configured, there are cache loader processes (cache loader) and cache manager processes (cache manager). All processes contain only one thread, and inter-process communication is mainly achieved through the mechanism of "shared memory". The main process runs as root, while worker, cache loader, and cache manager should all run as unprivileged users.

1. Install nginx

In the centos6 version of the epel source, nginx's rpm package has been added, but this rpm package version is lower. If you need an updated version, you can use the official rpm package, or you can use the source package to compile and install.

You can also use some secondary development enhanced nginx versions, such as Taobao's tengine and openresty are good choices.

1.1 Common compilation parameters

-- prefix=path: specify the installation directory for nginx

-- conf-path=path: specify the path to the nginx.conf configuration file

-- users of the user=name:nginx worker process

-- with-pcre: enable support for pcre regular expressions

-- with-http_ssl_module: launch support for ssl

-- with-http_stub_status_module: used to monitor the status of nginx

-- with-http-realip_module: allows you to change the client ip address in the client request header

-- with-file-aio: enable file aio

-- add-module=path: add third-party external modules

A complete compilation scheme is provided here:

-- prefix=/usr/local/nginx\

-- conf-path=/etc/nginx/nginx.conf\

-- error-log-path=/var/log/nginx/error.log\

-- http-log-path=/var/log/nginx/access.log\

-- http-client-body-temp-path=/var/tmp/nginx/client_body\

-- http-proxy-temp-path=/var/tmp/nginx/proxy\

-- http-fastcgi-temp-path=/var/tmp/nginx/fastcgi\

-- http-uwsgi-temp-path=/var/tmp/nginx/uwsgi\

-- pid-path=/var/run/nginx.pid\

-- lock-path=/var/lock/nginx\

-- user=nginx\

-- group=nginx\

-- with-file-aio\

-- with-http_ssl_module\

-- with-http_realip_module\

-- with-http_sub_module\

-- with-http_gzip_static_module\

-- with-http_stub_status_module\

-- with-pcre

1.2 startup and shutdown of nginx

Start nginx:

# nginx-c / etc/nginx/nginx.conf

Close nginx

# nginx-s stop

Reread the configuration file

# nginx-s reload# pkill-hup nginx

Reopen the log file

# nginx-s reopen# pkill-usr1 nginx

You can also download the / etc/init.d/nginx file in the nginx rpm package and use it after modifying the path:

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

2. Nginx.conf configuration file

The nginx configuration file is mainly divided into four parts: main (global settings), http (common settings for http), server (virtual host settings), and location (matching url paths). There are other configuration segments, such as event,upstream, etc.

2.1 General Settin

User nginx

Specify the users and groups running the nginx workre process

Worker_rlimit_nofile #

Specify the maximum number of files that all worker processes can open

Worker_cpu_affinity

Set the cpu stickiness of the worker process to avoid the performance consumption caused by the process switching between cpu. Such as worker_cpu_affinity 0001 0010 0100 1000; (quad core)

Worker_processes 4

The number of worker worker processes. This value can be set to the same number as cpu. If ssl and gzip are enabled, you can increase this value appropriately.

Worker_connections 1000

The maximum number of concurrent connections that can be accepted by a single worker process, in the event segment

Error_log logs/error.log info

The storage path and recording level of the error log

Use epoll

Using the epoll event model, put it in the event section

2.2 http Server

Server {}:

Define a virtual host

Listen 80

Define the address and port for listening. Default listening is on all addresses on this machine.

Server_name name [...]

Define virtual hostnames, which can use multiple names, as well as regular expressions or wildcards.

Sendfile on

Open the sendfile call to respond quickly to the client

Keepalive_timeout 65

Long connection timeout in seconds.

Send_timeout

Specify the timeout for the response client

Client_max_body_size 10m

Maximum size of the entity requested by the client

Root path

Set the root directory on the file system where the resource corresponding to the request url resides

Location [= | ~ | ~ * | ^ ~] uri {.}

Set a uri matching path

=: exact match

~: regular expression matching, case-sensitive characters

~ *: regular expressions match and are not case-sensitive

^ ~: the first half of uri matches, and regular expressions are not practical.

Priority:

= > location full path > ^ ~ > ~ * > location start path > location /

Allow and deny

Based on ip access control, such as:

Only allow 192.168.0.0amp 24 network segment client access

Allow 192.168.0.0/24

Deny all

Stub_status on

The enabled status is explicit and can only be used in location:

Open status explicit page

Location / status {stub_status on;allow 172.16.0.0 hand 16position deny all;}

Rewrite

Url rewriting, you can use a variety of tags

For example:

Rewrite ^ / images/ (. *\ .jpg) $/ imgs/$1 break

Available flag:

-last: continue to match other rewrite rules after rewriting

-break: do not continue matching after rewriting

-redirect: returns 302 redirection (temporary redirection), and the client initiates a new request for the redirected url

-permanent: returns 301redirection (permanent redirection), and the client initiates a new request for the redirected url

An example of server configuration:

Server {listen 80; server_name www.example.com; root / web/htdocs; location / {index index.html index.htm;} location / status {stub_status on; allow 10.0.0.0 8; deny all; access_log off;}

2.3 configuration of ssl

Enable one ssl virtual host

Server {listen 443; server_name example.com; root / apps/www; index index.html index.htm; ssl on; ssl_certificate / etc/nginx/ssl/nginx.crt; ssl_certificate_key / etc/nginx/ssl/nginx.key;# ssl_protocols sslv3 tlsv1 tlsv1.1 tlsv1.2;# ssl_ciphers all rips export56 RC4RSARSAR highlands; mediumRSAR lowrigsslv2veExport # ssl_prefer_server_ciphers on;}

Where ssl_certificate represents the ca file and ssl_certificate_key represents the key file.

If you want to force the http request to https, you can do this:

Server {listen 80th serverroomname example.me;return 301 https://$server_name$request_uri;}

2.4 nginx acts as a reverse proxy for load balancing

When nginx acts as a reverse proxy, there are multiple backend hosts. You can use upstream to define a backend host pool, and use the name of the host pool directly when reverse proxying. Load balancing scheduling algorithm, weight, health detection and other parameters can be defined in upstream.

For example:

Upstream backend {server 172.16.0.1:80 weight=1max-fails=3 fail_timeout=10; server 172.16.0.2:80 weight=1max-fails=3 fail_timeout=10;;}

Under the default request, the round-robin scheduling algorithm is used and has the ability to check and recover the health status of the host.

Ningx can also use these algorithms:

Ip_hash: based on the source address hash, the main purpose is session persistence

Least_conn: scheduling based on least active connections

Sticky: session binding based on cookie. Nginx inserts routing information into cookie when the client first accesses it, or selects the value of a field in cookie as the key, and each subsequent request will be scheduled based on this information.

There are three kinds of cookie-based session bindings: cookie,route and learn.

For example, cookie name-based scheduling:

Upstream backend {server backend1.example.com; server backend2.example.com; sticky cookie srv_id expires=1h domain=.example.com path=/;}

Use this host group for reverse proxy:

Location / {proxy_pass http://backend; proxy_set_header host $host; proxy_set_haeder x-forwared-for $proxy_add_x_forwarded_for;}

Proxy_pass url specifies the backend host of the agent. You can specify "http" or "https" protocols. The domain name can be ip address or upstream pool name.

If the agent specifies a uri address, such as http://127.0.0.1/remote, it will be proxied directly to the specified uri, regardless of the requested uri

If the agent specifies a host without a uri, such as http://127.0.0.1, the uri requested by the client will be passed to the specified domain name

If pattern matching url is used in location, the url is also passed to the end of the proxy url

If uri rewriting is used in location, proxy_pass will use the rewritten result for processing

Proxy_set_header header value modifies the header of the forwarded message

2.5 Cache-related settings when reverse proxying

Proxy_cache_path path [levels=levels] keys_zone=name:size

Define the disk cache path. The cache of nignx is stored in the form of key values. Keys_zone is used to specify the name and size of the memory space for keys, and the corresponding values are stored in the path specified by path. Levels can specify the level of cache storage path and the number of name characters. This setting can only be defined in the http section.

Such as:

Proxy_cache_path / var/cache/nginx/proxy levels=1:2 keys_zone=one:10m

Proxy_cache_valid [code...] Time specifies the cache time for the contents of different response codes

Such as:

Proxy_cache_valid 200302 10m any valid 404 1m

Proxy_cache_method method defines which method's request results can be cached, such as:

Proxy_cache_method get;proxy_cache_method head

Proxy_cache name specifies that a predefined cache space is used for caching

2.6Settings for fastcgi proxy

When using fastcgi, the method of setting up the proxy is similar to porxy_pass, but you can also use fastcgi caching, and the method of setting is similar to proxy_cache.

Location ~\ .php$ {root / web/htdocs; fastcgi_pass 127.0.0.1 root 9000; fastcgi_index index.php; fastcgi_param script_filename $document_root$fastcgi_script_name; include fastcgi_params;}

3. Some common built-in variables

$arg_name: request the name parameter in uri to

$args: all parameters of the request uri, same as $query_string

$uri: the uri of the current request, without parameters

$request_uri: the requested uri with full parameters

The host header in the $host:http request message. If there is no host header, it will be replaced by the hostname of the virtual host that processes the request

$hostname:nginx service runs on the hostname of the host

$remote_addr: client ip

$remote_port: client port

$remote_user: the user name entered by the client user when using user authentication

$request_filename: the local file path mapped by the uri in the user request after local root or alias conversion

$request_method: request method

$server_addr: server address

$server_name: server name

$server_port: server port

$server_protocol: the protocol when the server sends a response to the client, such as http/1.1,http/1.0

$scheme: the scheme used in the request, such as https in https://www.magedu.com/

$http_name: matches the specified header in the request message, such as $http_host matches the host header in the request message

$sent_http_name: matches the header specified in the response message, for example, $sent_content_type matches the content-type header in the response message

$status: response status

These are all the contents of the article "Nginx Server Building and basic configuration example Analysis". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.

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

Internet Technology

Wechat

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

12
Report