您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Nginx常用配置方法
## 一、Nginx基础概述
Nginx(发音为"engine x")是一款高性能的HTTP和反向代理服务器,由俄罗斯程序员Igor Sysoev开发。作为轻量级的Web服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,Nginx以高并发、低内存占用著称,全球约32.2%的网站使用Nginx作为Web服务器(数据来源:W3Techs)。
### 核心特性
- 事件驱动架构
- 非阻塞I/O模型
- 热部署能力
- 负载均衡支持
- 高扩展性
## 二、安装与基本命令
### 1. 安装方法(以Ubuntu为例)
```bash
# 添加官方仓库
sudo apt install curl gnupg2 ca-certificates lsb-release ubuntu-keyring
curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null
echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" | sudo tee /etc/apt/sources.list.d/nginx.list
# 安装Nginx
sudo apt update
sudo apt install nginx
# 启动服务
sudo systemctl start nginx
# 停止服务
sudo systemctl stop nginx
# 重启服务(加载新配置)
sudo systemctl restart nginx
# 重新加载配置(不中断服务)
sudo systemctl reload nginx
# 查看状态
sudo systemctl status nginx
# 设置开机启动
sudo systemctl enable nginx
Nginx配置文件通常位于/etc/nginx/nginx.conf
,主要包含三个上下文块:
main # 全局配置(影响所有模块)
events # 事件处理配置
http # HTTP服务器配置
典型配置层次:
http {
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html;
}
}
}
server {
listen 80;
server_name example.com;
root /var/www/example;
index index.html;
location / {
try_files $uri $uri/ =404;
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
}
}
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;
}
}
upstream backend {
server 192.168.1.100:8000 weight=3;
server 192.168.1.101:8000;
server 192.168.1.102:8000 backup;
}
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://backend;
}
}
支持算法: - 轮询(默认) - 加权轮询 - IP哈希 - 最少连接
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256...';
ssl_prefer_server_ciphers on;
location / {
root /var/www/html;
index index.html;
}
}
# HTTP强制跳转HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}
location /admin/ {
# 基础认证
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
# IP白名单
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
}
生成密码文件:
printf "username:$(openssl passwd -apr1)" > /etc/nginx/.htpasswd
events {
worker_connections 1024; # 每个worker最大连接数
multi_accept on; # 同时接受多个连接
use epoll; # Linux高性能事件模型
}
http {
sendfile on; # 启用零拷贝传输
tcp_nopush on; # 优化数据包发送
tcp_nodelay on; # 禁用Nagle算法
keepalive_timeout 65; # 保持连接超时
}
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_comp_level 6;
gzip_min_length 256;
gzip_proxied any;
gzip_vary on;
# 静态资源缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
# 代理缓存
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
}
}
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;
}
创建/etc/logrotate.d/nginx
:
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
server {
# 禁用server tokens
server_tokens off;
# 防止点击劫持
add_header X-Frame-Options "SAMEORIGIN";
# XSS防护
add_header X-XSS-Protection "1; mode=block";
# 内容安全策略
add_header Content-Security-Policy "default-src 'self'";
}
location /api/ {
limit_except GET POST {
deny all;
}
}
limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;
location /api/ {
limit_req zone=api_limit burst=20 nodelay;
}
# 测试配置语法
sudo nginx -t
# 查看加载的配置文件路径
sudo nginx -T
/var/log/nginx/error.log
(默认路径)error_log
指令自定义路径# 查看活跃连接
netstat -anp | grep nginx
# 查看进程状态
top -p $(pgrep nginx | tr '\n' ',' | sed 's/,$//')
location /ws/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
server {
listen 80;
server_name example.com www.example.com;
location / {
root /var/www/example;
}
}
server {
listen 80;
server_name blog.example.com;
location / {
proxy_pass http://localhost:2368;
}
}
error_page 404 /404.html;
location = /404.html {
root /usr/share/nginx/html;
internal;
}
本文涵盖了Nginx从基础安装到高级配置的多个方面,包括: 1. 静态资源服务配置 2. 反向代理与负载均衡 3. HTTPS安全配置 4. 性能优化技巧 5. 安全加固方案 6. 常见问题排查方法
实际生产环境中,建议:
- 使用nginx -t
测试所有配置变更
- 通过灰度发布逐步应用重大修改
- 定期检查错误日志和访问日志
- 保持Nginx版本更新以获得安全补丁
通过合理配置,Nginx可以轻松应对高并发场景,成为现代Web架构中不可或缺的组件。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。