Nginx 使用教程:从入门到核心配置
|
admin
2026年2月13日 12:0
本文热度 106
|
💥 你是不是也遇到过?
别担心!今天来带你从零玩转这个承载全球40%以上网站流量的高性能“引擎”!无论你是开发、运维还是实施,都能找到立刻用上的干货。
Nginx(发音为“engine-x”)是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP代理服务器。它以占用内存少、并发能力强而闻名。
高并发处理:使用事件驱动架构,支持数万并发连接
低内存消耗:静态资源处理高效
反向代理与负载均衡
热部署:支持不停止服务更新配置和二进制文件
# Ubuntu/Debian:
sudo apt update
sudo apt install nginx
# CentOS/RHEL:
sudo yum install epel-release
sudo yum install nginx
# macOS (使用Homebrew):
brew install nginx
# 启动Nginx
sudo systemctl start nginx
# 停止Nginx
sudo systemctl stop nginx
# 重启Nginx
sudo systemctl restart nginx
# 重新加载配置(不中断服务)
sudo systemctl reload nginx
# 设置开机启动
sudo systemctl enable nginx
# 检查配置语法
sudo nginx -t
/etc/nginx/
├── nginx.conf # 主配置文件
├── sites-available/ # 可用站点配置
├── sites-enabled/ # 已启用站点配置(符号链接)
├── conf.d/ # 额外配置文件
└── modules-available/ # 模块配置
# 全局块:影响Nginx整体运行的配置
user www-data;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
# Events块:影响Nginx与用户的网络连接
events {
worker_connections 1024;
use epoll;
}
# HTTP块:服务器相关配置
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 服务器块(虚拟主机)
server {
listen 80;
server_name example.com;
# 位置块:URL匹配和响应处理
location / {
root /var/www/html;
index index.html;
}
}
}
server {
listen 80;
server_name www.example.com;
root /var/www/example;
index index.html index.htm;
location / {
try_files $uri$uri/ =404;
}
# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
}
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:3000;
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_set_header X-Forwarded-Proto $scheme;
# 超时设置
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}
http {
upstream backend {
least_conn; # 最少连接算法
server backend1.example.com weight=3;
server backend2.example.com;
server backend3.example.com backup;
}
server {
listen 80;
location / {
proxy_pass http://backend;
}
}
}
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
# 增强安全性
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;
ssl_prefer_server_ciphers off;
# HSTS
add_header Strict-Transport-Security "max-age=63072000" always;
location / {
root /var/www/html;
}
}
# HTTP重定向到HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
location /admin {
# 基于IP的访问控制
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
# 基本认证
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
http {
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;
error_log /var/log/nginx/error.log warn;
# 按日期分割日志
map $time_iso8601$logdate {
'~^(?<ymd>\d{4}-\d{2}-\d{2})'$ymd;
default 'nodate';
}
access_log /var/log/nginx/access-$logdate.log main;
}
http {
# 限制请求频率
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
# 限制连接数
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
location /api/ {
limit_req zone=one burst=20;
limit_conn addr 10;
}
}
}
location /ws/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location /ws/ {
http {
geo $blocked_country {
default 0;
# 阻止特定国家访问
CN 1;
RU 1;
}
server {
if ($blocked_country = 1) {
return 403;
}
}
}
events {
worker_connections 4096;
multi_accept on;
use epoll;
}
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
keepalive_requests 100;
# 开启Gzip压缩
gzip on;
gzip_comp_level 5;
gzip_min_length 256;
gzip_types text/plain text/css application/json application/javascript;
}
http {
client_body_buffer_size 10K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 2 1k;
proxy_buffers 16 32k;
proxy_buffer_size 64k;
proxy_busy_buffers_size 128k;
}
# 检查配置语法
nginx -t
# 查看Nginx版本和编译参数
nginx -V
# 实时查看访问日志
tail -f /var/log/nginx/access.log
# 查看错误日志
tail -f /var/log/nginx/error.log
# 检查端口监听
sudo netstat -tulpn | grep nginx
问题1:权限错误
# 检查运行用户
ps aux | grep nginx
# 修复权限
sudo chown -R www-data:www-data /var/www
sudo chmod -R 755 /var/www
问题2:502 Bad Gateway
检查后端服务是否运行
检查防火墙设置
调整代理超时时间
本教程涵盖了Nginx的基础安装、核心配置和常用场景。要深入学习:
记住:每次修改配置后,先使用 nginx -t 测试语法,再使用 systemctl reload nginx 重载配置,避免服务中断。
该文章在 2026/2/13 12:02:37 编辑过