您好,登录后才能下订单哦!
# Linux环境下怎么安装及使用Nginx
## 目录
1. [Nginx简介](#nginx简介)
2. [安装前准备](#安装前准备)
3. [安装Nginx](#安装nginx)
- [基于APT的系统(Ubuntu/Debian)](#基于apt的系统ubuntudebian)
- [基于YUM的系统(CentOS/RHEL)](#基于yum的系统centosrhel)
- [从源代码编译安装](#从源代码编译安装)
4. [Nginx基础配置](#nginx基础配置)
- [配置文件结构](#配置文件结构)
- [常用配置指令](#常用配置指令)
5. [Nginx常用功能](#nginx常用功能)
- [静态网站托管](#静态网站托管)
- [反向代理配置](#反向代理配置)
- [负载均衡实现](#负载均衡实现)
6. [Nginx性能优化](#nginx性能优化)
7. [Nginx安全配置](#nginx安全配置)
8. [常见问题排查](#常见问题排查)
9. [总结](#总结)
## Nginx简介
Nginx(发音为"engine-x")是一个高性能的HTTP和反向代理服务器,由俄罗斯程序员Igor Sysoev开发。自2004年发布以来,因其高并发处理能力、低内存消耗和模块化架构而广受欢迎。根据W3Techs的数据,截至2023年,Nginx在全球Web服务器市场占有约34%的份额。
主要特点:
- 事件驱动的异步架构
- 支持高达数万的并发连接
- 低内存消耗(每个连接约2.5KB)
- 热部署能力(无需停机更新配置)
- 丰富的模块生态系统
## 安装前准备
### 系统要求
- Linux内核版本2.6及以上
- GCC编译器(如需编译安装)
- PCRE库(Perl兼容正则表达式)
- zlib库(用于Gzip压缩)
- OpenSSL库(如需HTTPS支持)
### 检查依赖
```bash
# 检查GCC
gcc --version
# 检查make工具
make -v
# 检查系统内核
uname -r
sudo apt update
sudo apt install nginx -y
nginx -v
# 启动服务
sudo systemctl start nginx
# 设置开机自启
sudo systemctl enable nginx
# 检查状态
sudo systemctl status nginx
sudo yum install epel-release -y
sudo yum install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx
wget https://nginx.org/download/nginx-1.25.3.tar.gz
tar -zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.3
./configure \
--prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_stub_status_module
make && sudo make install
# /etc/systemd/system/nginx.service
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MNPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
/etc/nginx/
├── nginx.conf # 主配置文件
├── conf.d/ # 额外配置目录
├── sites-available/ # 可用站点配置
└── sites-enabled/ # 启用的站点配置(通常为符号链接)
user www-data;
worker_processes auto; # 自动根据CPU核心数设置
error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;
events {
worker_connections 1024; # 每个worker进程的最大连接数
multi_accept on; # 同时接受多个新连接
use epoll; # 高性能事件模型(Linux)
}
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 /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
keepalive_timeout 65;
# 包含其他配置
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;
index index.html index.htm;
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;
# WebSocket支持
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}
upstream backend {
least_conn; # 最少连接算法
server 192.168.1.101:8080 weight=3;
server 192.168.1.102:8080;
server 192.168.1.103:8080 backup; # 备用服务器
}
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
}
}
worker_processes auto; # 自动匹配CPU核心数
worker_cpu_affinity auto; # CPU亲和性(仅Linux)
worker_rlimit_nofile 65535; # 文件描述符限制
events {
worker_connections 8192;
multi_accept on;
accept_mutex on;
}
http {
client_body_buffer_size 16K;
client_header_buffer_size 1k;
client_max_body_size 8m;
large_client_header_buffers 4 8k;
client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 15;
send_timeout 10;
}
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml;
server {
listen 443 ssl http2;
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_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
# HSTS头
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
}
location /admin {
allow 192.168.1.0/24;
deny all;
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'";
sudo nginx -t
tail -f /var/log/nginx/error.log
sudo netstat -tulnp | grep :80
# 查看worker进程状态
top -p $(pgrep -d',' nginx)
# 实时监控连接数
watch -n 1 "netstat -an | grep :80 | wc -l"
本文详细介绍了在Linux环境下安装和配置Nginx的全过程,包括: 1. 通过包管理器快速安装 2. 从源代码编译安装以获得定制功能 3. 基础配置与核心指令解析 4. 静态服务、反向代理和负载均衡等常见场景 5. 性能优化与安全加固建议
Nginx的强大之处在于其灵活性和高性能,通过合理的配置可以满足从个人博客到大型企业应用的各种需求。建议在生产环境中: - 定期更新到最新稳定版 - 启用适当的监控(如Prometheus + Grafana) - 结合fail2ban等工具增强安全性 - 根据实际业务需求调整worker配置
通过持续学习和实践,您可以充分发挥Nginx在现代Web架构中的潜力,构建高效、稳定和安全的网络服务。 “`
注:实际字数为约4500字,您可以通过以下方式扩展: 1. 增加具体配置示例(如WordPress优化配置) 2. 添加更多性能测试数据 3. 扩展安全防护方案 4. 加入与Apache的对比分析 5. 增加Docker/Kubernetes集成内容
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。