配置案例
大约 2 分钟
简单静态文件访问配置
通过访问 http://localhost/blog
访问 /home/user/blog
目录下的资源。
使用 root 指令
http {
#... ...
# 虚拟主机配置
server {
# 监听端口
listen 80;
# 服务主机名
server_name localhost;
location /blog/ {
# 本地文件目录
root /home/user;
# 首页文件,访问 http://localhost/ 默认访问 index.html 文件
index index.html;
# 不匹配返回 404 状态码
try_files $uri $uri/ =404;
}
}
#... ...
}
使用 alias 指令
http {
#... ...
# 虚拟主机配置
server {
# 监听端口
listen 80;
# 服务主机名
server_name localhost;
location /blog/ {
# 本地文件目录
alias /home/user/blog/;
# 首页文件,访问 http://localhost/ 默认访问 index.html 文件
index index.html;
# 不匹配返回 404 状态码
try_files $uri $uri/ =404;
}
}
#... ...
}
反向代理
将请求代理到本地服务器
将 http://example.com/api/get/list
请求转发到 http://localhost:8080/api/get/list
。
server {
listen 80;
server_name example.com;
location /api {
# 代理地址
proxy_pass http://localhost:8080/api;
# 设置请求头信息
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
如果后端服务需使用 https,在上述案例中那个,将 http://localhost:8080/api
改为 https://localhost:8080/api
即可。
负载均衡反向代理
http {
upstream backend_cluster {
server http://localhost:8080/api;
server http://localhost:8081/api;
}
server {
listen 80;
server_name example.com;
location /api {
proxy_pass http://backend_cluster;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
- upstream backend_cluster:定义一个上游服务器组,其中包括
http://localhost:8080/api
和http://localhost:8081/api
两个后端服务器。 - 负载均衡策略:Nginx 默认使用轮询策略,即将请求依次转发给
http://localhost:8080/api
和http://localhost:8081/api
,可以通过配置如least_conn
或ip_hash
等改变策略。
反向代理常用命令
- proxy_redirect: 用来修改后端返回的 Location 和 Refresh 头中的 URL,适用于后端返回的重定向 URL 不正确的情况。
proxy_redirect http://backend_server/ /;
如果后端服务器返回 http://backend_server/redirect
, Nginx 会将其替换为 http://example.com/redirect
。
- proxy_read_timeout: 指定从后端服务器读取响应的超时时间。
proxy_read_timeout 90s;
- proxy_connect_timeout: 指定 Nginx 连接后端服务器的超时时间。
proxy_connect_timeout 30s;
- proxy_buffering: 控制是否启用缓冲。启用缓冲可以提升性能,但可能会增加延迟。
proxy_buffering on;