Nginx 是一个高性能的 HTTP 和反向代理服务器,配置 Nginx 通常涉及以下几个步骤:
安装 Nginx
Ubuntu/Debian:
sudo apt update
sudo apt install nginx
CentOS/RHEL:
sudo yum install nginx
MacOS(使用 Homebrew):
brew install nginx
配置 Nginx
基本配置文件位置
Nginx 主配置文件通常位于 `/etc/nginx/nginx.conf`。
配置文件示例
worker_processes auto; 工作进程数,自动根据 CPU 核心数设置
error_log /var/log/nginx/error.log warn; 错误日志文件路径及级别
pid /var/run/nginx.pid; 进程 ID 文件路径
events {
worker_connections 1024; 每个工作进程的最大并发连接数
}
http {
include /etc/nginx/mime.types; MIME 类型定义文件
default_type application/octet-stream; 默认 MIME 类型
log_format access '$remote_addr - $remote_user [$time_local] $host $request "$status" $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for" $clientip'; 日志格式
access_log /var/log/nginx/access.log access; 日志输出目录
gzip on; 启用 gzip 压缩
sendfile on; 启用 sendfile
}
server {
listen 80; 监听 80 端口
server_name example.com; 域名
location / {
root /var/www/html; 静态文件目录
index index.html index.htm; 默认索引文件
}
}
启动和停止 Nginx
启动 Nginx 服务:
sudo systemctl start nginx
停止 Nginx 服务:
sudo systemctl stop nginx
重新加载配置文件(热加载):
sudo systemctl reload nginx
检查配置文件语法
nginx -t
验证 Nginx 是否运行
sudo systemctl status nginx
注意事项
确保 Nginx 用户有足够的权限访问配置文件和相关目录。
配置文件中的 `worker_processes` 应根据服务器的 CPU 核心数进行调整。
`worker_connections` 决定了每个工作进程可以同时处理的连接数。
配置文件中的日志路径应根据实际情况进行调整。
以上是基本的 Nginx 配置流程。根据具体需求,你可能需要调整更多配置项,例如设置虚拟主机、启用 gzip 压缩、配置 HTTPS 等。