Nginx 是一種開源的高性能 HTTP 伺服器和反向代理伺服器,可用於配置和管理 Web 應用程式的流量。以下是一些 Nginx 配置示例:
- 用 Nginx 作為 Web 伺服器
server {
listen 80;
server_name example.com;
root /var/www/html/example;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
在此示例中,Nginx 被配置為監聽 80 端口,並將請求重定向到 /var/www/html/example 目錄中的 index.html 文件。如果請求的文件不存在,則會返回 404 錯誤。
- 反向代理伺服器
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
在此示例中,Nginx 被配置為將請求轉發到本地主機上的 8080 端口。通過設置 proxy_set_header,可以將原始請求中的信息(如主機名和 IP 地址)傳遞給後端伺服器。
- 負載均衡
upstream backend {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}
server {
listen 80;
location / {
proxy_pass http://backend;
}
}
在此示例中,使用 upstream 指令定義了一個名為 backend 的負載均衡器,該負載均衡器將請求分發到 3 個後端伺服器。在 server 程式碼塊中,proxy_pass 指令用於將請求轉發到負載均衡器。