nginx.conf
配置内容
# Nginx 运行用户(Windows 下可省略,默认使用系统用户)
# user nobody;
# 工作进程数(建议设置为 CPU 核心数)
worker_processes 1;
# 错误日志路径(Windows 路径使用 / 或 \\)
error_log logs/error.log;
# error_log logs/error.log notice;
# error_log logs/error.log info;
# 进程 PID 文件
pid logs/nginx.pid;
events {
# 每个工作进程的最大连接数
worker_connections 1024;
}
http {
# MIME 类型配置
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 logs/access.log main;
# 发送文件优化
sendfile on;
# tcp_nopush on;
# 连接超时时间
keepalive_timeout 65;
# 开启 gzip 压缩
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 5;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_vary on;
# 服务器配置(端口 9999)
server {
# 监听端口
listen 9999;
# 服务器名称(Windows 本地可留空或填 localhost)
server_name localhost;
# 字符集设置
charset utf-8;
# 静态资源配置(核心)
location / {
# 指向 Windows 下的静态资源目录(注意路径用 / 分隔)
root D:/upload;
# 默认索引文件(如果访问目录时自动查找的文件)
index index.html index.htm;
# 允许浏览器缓存静态资源(可选优化)
expires 1d;
}
# 处理 404 错误
error_page 404 /404.html;
location = /404.html {
root D:/upload; # 404 页面也从静态资源目录读取
}
# 处理 500 系列错误
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html; # Nginx 自带的 50x 页面,位于 Nginx 安装目录的 html 文件夹
}
}
}
配置说明
-
核心配置解析:
listen 9999
:指定 Nginx 监听 9999 端口。root D:/upload
:将http://localhost:9999/
根路径映射到本地D:\upload
目录,访问http://localhost:9999/xxx.jpg
会对应到D:\upload\xxx.jpg
。index
:设置目录默认索引文件(如index.html
)。
-
路径注意事项:
- Windows 路径中的反斜杠
\
需替换为/
或\\
(配置中使用D:/upload
更简洁)。 - 确保
D:\upload
目录已存在,否则访问时会报 403 错误。
- Windows 路径中的反斜杠
-
优化配置:
- 开启
gzip
压缩:减少静态资源传输大小,提升加载速度。 expires 1d
:设置浏览器缓存静态资源 1 天,减少重复请求。- 错误页面处理:404 页面从
D:/upload
读取,50x 错误使用 Nginx 自带页面。
- 开启
使用方法
- 找到你的 Nginx 安装目录(如
C:\nginx-1.24.0
),打开conf
文件夹,替换其中的nginx.conf
文件内容为上述配置。 - 启动 Nginx:
- 在 Nginx 安装目录的
cmd
窗口中执行start nginx
。 - 验证是否启动成功:访问
http://localhost:9999
,若D:\upload
中有index.html
会显示该页面,否则显示目录列表(若目录有文件)。
- 在 Nginx 安装目录的
- 重启 / 停止 Nginx:
- 重启:
nginx -s reload
- 停止:
nginx -s stop
- 重启: