Nginx 安装 与 配置
Nginx 简介
Nginx 是一个高性能的 HTTP 和反向代理 Web 服务器,同时也提供了 IMAP/POP3/SMTP 服务。Nginx 是由伊戈尔·赛索耶夫为俄罗斯访问量第二的 Rambler.ru 站点开发的,第一个公开版本发布于 2004 年 10 月 4 日。
Nginx 的主要特点:
- 高并发连接:官方测试能够支撑 5 万并发连接
- 内存消耗少:10 万个非活跃的 HTTP keep-alive 连接仅消耗 2.5MB 内存
- 高可靠性:主从热备
- 支持热部署:不停止服务的情况下升级
- 支持多种协议:HTTP、HTTPS、SMTP、POP3、IMAP 等
Nginx 安装(Ubuntu)
方法一:使用 apt 安装
- 更新软件包列表:
sudo apt update
- 安装 Nginx:
sudo apt install nginx
- 验证安装:
nginx -v
- 启动 Nginx 服务:
sudo systemctl start nginx
- 设置开机自启:
sudo systemctl enable nginx
方法二:从源码编译安装(灵活性高)
- 安装依赖包:
安装 gcc
sudo apt install gcc
安装 pcre 库
sudo apt install libpcre3 libpcre3-dev
安装 SSL 库
sudo apt-get install openssl libssl-dev
- 下载 Nginx 源码:
wget http://nginx.org/download/nginx-1.26.1.tar.gz
tar -zxvf nginx-1.26.1.tar.gz
cd nginx-1.26.1
- 配置编译选项:
--prefix 可更改编译安装地址 编译并指定安装位置,(安装目录不能和编译目录为同一文件夹)
./configure --prefix=/usr/local/nginx \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_stub_status_module
- 编译和安装:
进入编译安装地址
make
sudo make install
Nginx 配置
基本配置结构
Nginx 的主配置文件通常位于 /etc/nginx/nginx.conf,主要包含以下部分:
- 全局配置块:
user www-data;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
- events 块:
events {
worker_connections 1024;
multi_accept on;
}
- http 块:
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;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# 包含其他配置文件
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
常用配置示例
- 静态网站配置:
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
- 反向代理配置:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
常用命令
- 启动 Nginx:
sudo systemctl start nginx
- 停止 Nginx:
sudo systemctl stop nginx
- 重启 Nginx:
sudo systemctl restart nginx
- 重新加载配置:
sudo nginx -s reload
- 检查配置文件语法:
sudo nginx -t
安全建议
- 及时更新 Nginx 版本
- 配置 SSL/TLS 证书
- 使用防火墙限制访问
- 禁用不必要的模块
- 配置适当的访问控制
- 定期检查日志文件
