Nginx 是一款高性能的 HTTP 和反向代理服务器,它的配置文件通常分为几个部分,包括主配置文件和默认的虚拟主机配置文件。以下是 Nginx 配置文件的基本结构和一些常用设置的示例:
主配置文件位置
- Linux: 通常位于
/etc/nginx/nginx.conf
。 - macOS: 如果通过 Homebrew 安装,通常位于
/usr/local/etc/nginx/nginx.conf
。
基本配置文件结构
# 用户和组
user www-data;
worker_processes auto;
# 错误日志文件
error_log /var/log/nginx/error.log warn;
# 进程PID文件
pid /var/run/nginx.pid;
# 事件模块配置
events {
worker_connections 1024;
}
# 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;
# 打开文件缓存
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 60s;
open_file_cache_min_uses 1;
open_file_cache_errors off;
# 负载均衡连接超时
keepalive_timeout 65;
# 包含默认虚拟主机配置文件
include /etc/nginx/conf.d/*.conf;
# 包含所有的虚拟主机配置文件
include /etc/nginx/sites-enabled/*;
}
默认虚拟主机配置
默认的虚拟主机配置文件通常位于 /etc/nginx/conf.d/default.conf
或者 /etc/nginx/sites-enabled/000-default.conf
,取决于你的系统和 Nginx 的安装方式。以下是一个虚拟主机的基本配置示例:
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name localhost;
# 网站根目录
root /var/www/html;
index index.html index.htm index.nginx-debian.html;
# 日志文件
access_log /var/log/nginx/host.access.log main;
error_log /var/log/nginx/error.log;
location / {
try_files $uri $uri/ =404;
}
}
配置 SSL
如果需要为网站配置 SSL,可以添加如下配置:
server {
listen 443 ssl http2;
keepalive_timeout 70;
server_name example.com;
# SSL 证书和密钥文件
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# SSL 配置
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;
# 其他配置...
}
重启 Nginx 服务
配置文件修改后,需要重启 Nginx 服务以使更改生效:
sudo systemctl restart nginx
或者
sudo service nginx restart
提示,配置文件的确切位置和内容可能会因操作系统、Nginx 版本和个人配置而有所不同。在进行任何更改之前,建议备份原始配置文件。