随着互联网的快速发展,用户对网站和应用的响应速度、并发处理能力以及可靠性的要求越来越高。传统的 Web 服务器在面对大规模并发请求时往往显得力不从心,而 Nginx 以其高效的事件驱动模型、优秀的反向代理功能以及灵活的配置选项,为解决这些问题提供了强大的解决方案。无论是构建高流量的网站、实现负载均衡,还是进行安全防护,Nginx 都能发挥重要作用。
Nginx(Engine X)是一款开源的高性能 Web 服务器和反向代理服务器,同时也可以作为邮件代理服务器和通用的 TCP/UDP 代理服务器。它由俄罗斯的程序员 Igor Sysoev 开发,于 2004 年首次公开发布。Nginx 以其轻量级、高性能、高并发处理能力和低内存消耗等特点而闻名,被广泛应用于各种规模的网站和应用中。
sudo apt update
sudo apt install nginx
nginx -v
nginx -v
nginx.conf
,它通常位于 Nginx 的安装目录下。nginx.conf
文件由多个部分组成,包括全局块、events 块、http 块等。user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/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 /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
}
localhost
。它将/usr/share/nginx/html
目录作为静态文件根目录,并定义了错误页面的处理方式。http {
include /etc/nginx/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 /var/log/nginx/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name example.com;
location / {
root /var/www/example.com;
index index.html index.htm;
}
}
server {
listen 80;
server_name another-example.com;
location / {
root /var/www/another-example.com;
index index.html index.htm;
}
}
}
example.com
和another-example.com
两个域名。每个虚拟主机都有自己的根目录和默认首页。http {
upstream backend {
server backend1.example.com:8080;
server backend2.example.com:8080;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
}
}
}
backend
的上游服务器组,包含两个后端服务器backend1.example.com:8080
和backend2.example.com:8080
。然后,在虚拟主机的配置中,将所有请求都转发到这个上游服务器组上,实现了负载均衡的功能。http {
upstream backend {
server backend1.example.com:8080 weight=3;
server backend2.example.com:8080 weight=2;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
}
}
}
backend
的上游服务器组,包含两个后端服务器backend1.example.com:8080
和backend2.example.com:8080
。其中,backend1.example.com:8080
的权重为 3,backend2.example.com:8080
的权重为 2。Nginx 会根据权重的比例将请求分发到不同的后端服务器上,实现了加权轮询负载均衡的功能。http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
listen 80;
server_name example.com;
location / {
proxy_cache my_cache;
proxy_pass http://backend;
}
}
}
/var/cache/nginx
,并创建了一个名为my_cache
的缓存区域。然后,在虚拟主机的配置中,将缓存区域应用到请求处理中,实现了缓存功能。Nginx 会将后端服务器的响应内容缓存到指定的缓存路径中,并根据配置的参数进行管理和清除。http {
server {
listen 80;
server_name static.example.com;
location / {
root /var/www/static;
}
}
}
static.example.com
。它将/var/www/static
目录作为静态文件根目录,当客户端请求静态文件时,Nginx 会直接从这个目录中读取文件内容并返回给客户端。http {
upstream backend {
server backend1.example.com:8080;
server backend2.example.com:8080;
server backend3.example.com:8080;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
}
}
}
backend
的上游服务器组,包含三个后端服务器backend1.example.com:8080
、backend2.example.com:8080
和backend3.example.com:8080
。然后,在虚拟主机的配置中,将所有请求都转发到这个上游服务器组上,实现了负载均衡的功能。Nginx 会根据配置的负载均衡算法将请求分发到不同的后端服务器上。events {
worker_connections 10240;
use epoll;
}
http {
keepalive_timeout 65;
tcp_nodelay on;
gzip on;
open_file_cache max=100000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}
worker_connections
参数设置了每个工作进程的最大连接数,use epoll
参数指定了使用 epoll 事件驱动模型,keepalive_timeout
参数设置了长连接的超时时间,tcp_nodelay
参数开启了 TCP_NODELAY 选项,以减少网络延迟,gzip on
参数开启了 Gzip 压缩功能,以减少网络传输的数据量,open_file_cache
参数设置了文件缓存的相关参数,以提高文件读取的性能。收起
nginx
复制
http {
# 访问控制
location /admin {
deny all;
}
location /api {
allow 192.168.1.0/24;
deny all;
}
# IP 过滤
valid_referers none blocked *.example.com;
if ($invalid_referer) {
return 403;
}
# SSL/TLS 加密
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/nginx/ssl/example.crt;
ssl_certificate_key /etc/nginx/ssl/example.key;
location / {
#...
}
}
}
location
块实现了访问控制功能,禁止所有用户访问/admin
目录,只允许来自192.168.1.0/24
网段的用户访问/api
目录。通过valid_referers
指令和if
语句实现了 IP 过滤功能,只允许来自特定域名的请求访问网站。通过server
块实现了 SSL/TLS 加密功能,将网站的访问端口设置为 443,并指定了 SSL 证书和私钥的路径。http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
listen 80;
server_name example.com;
location / {
proxy_cache my_cache;
proxy_pass http://backend;
}
location ~* \.(jpg|jpeg|png|gif|css|js)$ {
expires 30d;
add_header Cache-Control "public";
}
}
}
http {
server {
listen 80;
server_name example.com;
location /static/ {
root /var/www/static;
}
location / {
proxy_pass http://backend;
}
}
}
/static/
开头的请求直接从/var/www/static
目录中返回静态资源,而其他请求则转发到后端的动态服务器上。#include
#include
#include
static ngx_int_t ngx_http_myfilter_handler(ngx_http_request_t *r);
static ngx_http_module_t ngx_http_myfilter_module_ctx = {
NULL, /* preconfiguration */
NULL, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
NULL, /* create location configuration */
NULL /* merge location configuration */
};
static ngx_command_t ngx_http_myfilter_commands[] = {
{ ngx_string("my_filter"),
NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS,
ngx_http_myfilter_handler,
0,
0,
NULL },
ngx_null_command
};
ngx_module_t ngx_http_myfilter_module = {
NGX_MODULE_V1,
&ngx_http_myfilter_module_ctx, /* module context */
ngx_http_myfilter_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static ngx_int_t ngx_http_myfilter_handler(ngx_http_request_t *r)
{
ngx_buf_t *b;
ngx_chain_t out;
// 添加自定义的处理逻辑
return NGX_OK;
}
ngx_http_myfilter_module
的 Nginx HTTP 模块,实现了一个名为my_filter
的指令。当 Nginx 处理 HTTP 请求时,如果遇到这个指令,就会调用ngx_http_myfilter_handler
函数进行处理。可以在这个函数中添加自定义的处理逻辑,实现特定的功能。http {
upstream microservices {
server microservice1.example.com:8080;
server microservice2.example.com:8080;
}
server {
listen 80;
server_name api.example.com;
location /service1/ {
rewrite ^/service1/(.*)$ /$1 break;
proxy_pass http://microservices;
}
location /service2/ {
rewrite ^/service2/(.*)$ /$1 break;
proxy_pass http://microservices;
}
}
}
microservices
的上游服务器组,包含两个微服务实例microservice1.example.com:8080
和microservice2.example.com:8080
。然后,在虚拟主机的配置中,通过location
块和rewrite
指令实现了请求的路由功能,将不同的请求转发到相应的微服务实例上。# 主服务器配置
http {
upstream backend {
server backend1.example.com:8080;
server backend2.example.com:8080;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
}
}
}
# 从服务器配置
http {
upstream backend {
server backend1.example.com:8080;
server backend2.example.com:8080;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
}
}
}
worker_connections
参数,设置每个工作进程的最大连接数。根据服务器的内存和负载情况,合理设置这个参数,以避免连接过多导致系统资源耗尽。worker_processes
参数,将工作进程数设置为与服务器的 CPU 核心数相等或稍多一些,以充分利用多核处理器的性能。Nginx 作为一款高性能的 Web 服务器和反向代理服务器,在互联网领域中发挥着重要的作用。本文详细介绍了 Nginx 的基础概念、安装与配置、常见应用场景、高级功能以及性能优化等方面的内容,并通过丰富的示例帮助读者更好地理解和应用 Nginx。通过掌握 Nginx 的使用,开发者可以构建出高效、可靠、安全的网站和应用,满足不断增长的业务需求。