Nginx 反向代理
location 指令说明
location [ = | ~ | ~* | ^~ ] uri {
}
- = :用于不含正则表达式的 uri 前,要求请求字符串与 uri 严格匹配,如果匹配成功,就停止继续向下搜索并立即处理该请求
- ~ :用于表示 uri 包含正则表达式,并且区分大小写
- !~:用于表示 uri 不含正则表达式,并且区分大小写
- ~* :用于表示 uri 包含正则表达式,并且不区分大小写
- !~*:用于表示 uri 不含正则表达式,并且不区分大小写
- ^~ :用于不含正则表达式的 uri 前,要求 Nginx 服务器找到标识 uri 和请求字符串匹配度最高的 location 后,立即使用此 location 处理请求,而不再使用 location 块中的正则 uri 和请求字符串做匹配
注意:如果 uri 包含正则表达式,则必须要有 ~ 或者 ~* 标识。
因此,大类型可以分为 3 种匹配模式
- location = patt {} [精准匹配]
- location patt {} [一般匹配]
- location ~ patt {} [正则匹配]
location = / {
# 只匹配 / 查询。
}
location / {
# 匹配任何查询,因为所有请求都以 / 开头。但是正则表达式规则和长的块规则将被优先和查询匹配。
}
location ^~ /images/ {
# 匹配任何以 /images/ 开头的任何查询并且停止搜索。任何正则表达式将不会被测试。
}
location ~*.(gif|jpg|jpeg)$ {
# 匹配任何以 gif、jpg 或 jpeg 结尾的请求。
}
location ~*.(gif|jpg|swf)$ {
valid_referers none blocked start.igrow.cn sta.igrow.cn;
if ($invalid_referer) {
#防盗链
rewrite ^/ http://$host/logo.png;
}
}
192.168.0.107:80 -> 127.0.0.1:8080
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name 192.168.0.107;
location / {
proxy_pass http://127.0.0.1:8080;
}
}
}

http://192.168.0.107:9001/docs/ -> 127.0.0.1:8080
http://192.168.0.107:9001/examples/ -> 127.0.0.1:8081
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 9001;
server_name 192.168.0.107;
location / {
root html;
index index.html index.htm;
}
location ~ /docs/ {
proxy_pass http://127.0.0.1:8080;
}
location ~ /examples/ {
proxy_pass http://127.0.0.1:8081;
}
}
}

后端路径为 /api,前端路径为 /api/app
#user nobody;
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 1234;
server_name 127.0.0.1;
location = /api {
rewrite ^ /api/app;
}
location = /api/ {
rewrite ^ /api/app;
}
location ^~ /api/app {
alias /opt/nginx-1.18.0/api/html;
try_files $uri $uri/ /index.html;
# index index.html;
}
location /api {
proxy_pass http://127.0.0.1:8848/api;
client_max_body_size 1024m;
proxy_set_header Origin '';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
https://nginx.org/en/docs/http/ngx_http_core_module.html#location

浙公网安备 33010602011771号