主题
语法
配置文件结构
Nginx 的配置文件通常位于 /etc/nginx/nginx.conf,其基本结构如下:
nginx
# 全局块
user nginx;
worker_processes auto;
# 事件块
events {
worker_connections 1024;
}
# HTTP 块
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 服务器块
server {
listen 80;
server_name example.com;
# 位置块
location / {
root /usr/share/nginx/html;
index index.html;
}
}
}HTTP 配置
常见指令
include: 引入其他配置文件。nginxinclude /etc/nginx/mime.types;default_type: 设置默认 MIME 类型。nginxdefault_type application/octet-stream;sendfile: 启用高效文件传输。nginxsendfile on;keepalive_timeout: 设置客户端连接的超时时间。nginxkeepalive_timeout 65;
Server 配置
常见指令
listen: 指定监听的端口。nginxlisten 80;server_name: 定义服务器名称。nginxserver_name example.com;error_page: 自定义错误页面。nginxerror_page 404 /404.html;access_log和error_log: 定义访问日志和错误日志路径。nginxaccess_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log;
Location 配置
常见指令
root: 设置根目录。nginxlocation / { root /usr/share/nginx/html; }index: 指定默认首页文件。nginxlocation / { index index.html; }proxy_pass: 转发请求到后端服务器。nginxlocation /api/ { proxy_pass http://127.0.0.1:3000; }rewrite: URL 重写。nginxlocation /old-path/ { rewrite ^/old-path/(.*)$ /new-path/$1 permanent; }try_files: 尝试访问文件或返回指定内容。nginxlocation / { try_files $uri $uri/ =404; }
Upstream 配置
常见指令
upstream: 定义后端服务器组,用于负载均衡。nginxupstream backend { server 127.0.0.1:8080; server 127.0.0.1:8081; }- 在
server块中使用proxy_pass指向upstream。nginxserver { listen 80; location / { proxy_pass http://backend; } }
