Nginx 配置详解
配置文件结构
/etc/nginx/nginx.conf
# ── 全局块 ──
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;
# ── events 块 ──
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" '
'$request_time $upstream_response_time';
access_log /var/log/nginx/access.log main;
# ── server 块(虚拟主机)──
include /etc/nginx/conf.d/*.conf;
}
server 与 location
conf.d/example.conf
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example;
index index.html;
# 精确匹配(优先级最高)
location = /health {
return 200 'OK';
add_header Content-Type text/plain;
}
# 前缀匹配(^~ 停止正则搜索)
location ^~ /static/ {
expires 30d;
access_log off;
}
# 正则匹配(区分大小写)
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params;
}
# 正则匹配(不区分大小写)
location ~* \.(jpg|png|gif)$ {
expires 7d;
}
# 通用前缀匹配(优先级最低)
location / {
try_files $uri $uri/ /index.html;
}
}
location 匹配优先级
= 精确匹配 > ^~ 前缀匹配 > ~ 正则匹配 > ~* 正则(不区分大小写) > / 通用前缀
常用变量
| 变量 | 说明 |
|---|---|
$host | 请求的主机名 |
$remote_addr | 客户端 IP |
$request_uri | 完整请求 URI(含参数) |
$uri | 当前 URI(不含参数,可被 rewrite 修改) |
$args | 查询字符串 |
$scheme | http 或 https |
$request_time | 请求处理时间(秒) |
$upstream_response_time | 后端响应时间 |
常见面试问题
Q1: try_files 的作用?
答案:try_files $uri $uri/ /index.html; 依次尝试:① 请求的文件 → ② 请求的目录 → ③ 回退到 /index.html。这是 SPA 应用的标准配置,确保前端路由刷新时不返回 404。
Q2: 如何配置多域名虚拟主机?
答案:每个域名一个 server 块,通过 server_name 区分。Nginx 根据请求的 Host 头匹配对应 server 块。匹配不到时走 default_server。
server {
listen 80 default_server;
return 444; # 拒绝未匹配的请求
}