一张图读懂 nginx.conf:从入门到精通的 5 个核心配置块
Nginx 的 nginx.conf 看起来复杂,其实核心就五个配置块:main、events、http、server、location。把这五个搞明白,Nginx 就算入门了。
其中最让人头疼的是 location 的匹配规则。什么时候用 =,什么时候用 ^~,正则匹配怎么生效,很多人配完心里都没底。
这篇文章把 nginx.conf 的结构拆开讲清楚,把 location 匹配规则说明白。
Nginx 是现代 Web 服务的“交通枢纽”,负责接收所有请求,然后根据配置精准分发给对应的服务(静态文件、后端应用、缓存服务器等)。
选择它的理由:
nginx.conf 的骨架:从外到内的五个核心块Nginx 的配置文件从外到内,层层嵌套:
# 第一层:全局块 (main)
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
# 第二层:事件块 (events)
events {
worker_connections 1024;
}
# 第三层:HTTP块 (http)
http {
# HTTP全局配置
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 第四层:Server块 (server)
server {
listen 80;
server_name localhost;
# 第五层:Location块 (location)
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
}
各层级的作用:
最常配置
location 匹配规则location 决定了一个请求 URL 应该由哪个块来处理。
匹配语法与优先级
location = /path最高 location ^~ /static/次高 location ~ \.php$location /最低
核心规则:
=、^~、普通)=),直接使用,结束~、~*)案例:一个域名下的两个服务
假设要配 www.example.com:
/var/www/htmlhttp://127.0.0.1:3000server {
listen 80;
server_name www.example.com;
location / {
root /var/www/html;
index index.html;
}
location /api/ {
proxy_pass http://127.0.0.1:3000/;
proxy_set_header Host $host;
}
}
用户访问 www.example.com/api/users:
location / 和 location /api/ 都匹配/api//api/ → 代理转发成功几点建议:
location ^~ /path/ 做路径明确的静态资源和 API 路由,跳过正则匹配,效率更高.php 文件、图片防盗链= 用于精准路径,如网站根路径或特殊页面location = / 拦截敏感文件# 精确匹配根路径
location = / {
root /var/www/project;
index index.html;
}
# 拦截 .git 目录
location ~ /\.git {
deny all;
return 403;
}
# 其他请求正常处理
location / {
root /var/www/project;
try_files $uri $uri/ /index.html;
}
location = / 优先级最高,根路径请求不受后面规则干扰。正则匹配 ~ /\.git 拦截所有带 .git 的路径。
try_files + 命名 location 实现“静态优先,动态兜底”location /blog/ {
root /var/www/blog-static;
try_files $uri $uri/ @backend;
}
location @backend {
proxy_pass http://127.0.0.1:3000;
}
请求先找静态文件,找到了直接返回;找不到就自动跳转到 @backend 代理给后端。整个过程不用 if,逻辑清晰。在旧项目迁移时这个很好用。
location / { root /path; index index.html; }location ^~ /static/ { root /path; }location ^~ /api/ { proxy_pass http://backend; }location ~ \.php$ { fastcgi_pass ...; }
每次新项目直接复制,改改路径和端口就能用:
server {
listen 80;
server_name your-domain.com;
access_log /var/log/nginx/your-domain.com.access.log;
location / {
root /var/www/your-project/frontend;
try_files $uri $uri/ /index.html;
}
location ^~ /api/ {
proxy_pass http://127.0.0.1:3000/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
阅读原文:原文链接