Nginx 是一個高性能的 HTTP 和反向代理服務器,除了基本的 Web 服務功能外,它還支持許多高級功能。以下是 Nginx 常用的一些功能及其設置方法:
1. 反向代理
反向代理是 Nginx 最常用的功能之一,用于將客戶端請求轉發給后端服務器,并返回處理結果。http {
? ? limit_req_zone $binary_remote_addr zone=admin_limit:10m rate=10r/m;? ? server {
? ? ? ? listen 80;
? ? ? ? server_name example.com;? ? ? ? location /admin/ {
? ? ? ? ? ? allow 192.168.1.0/24; # 僅允許特定網段訪問
? ? ? ? ? ? deny all; ? ? ? ? ? ? ?# 拒絕其他所有來源
? ? ? ? ? ??
? ? ? ? ? ? limit_req zone=admin_limit burst=5 nodelay;
? ? ? ? ? ??
? ? ? ? ? ? proxy_pass http://backend_admin_server;
? ? ? ? ? ? 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;
? ? ? ? }
? ? }
}例子2:
server {
? ? listen 80;
? ? server_name yourdomain.com;? ? # 定義圖片存儲路徑
? ? location /images/ {
? ? ? ? root /path/to/local/images; # 設置本地圖片存儲路徑
? ? ? ? try_files $uri @minio; # 如果本地找不到圖片,則轉到 @minio 處理
? ? }? ??
? ? location @minio {
? ? ? ? proxy_pass http://minio-server-endpoint; # 替換為你的 MinIO 服務器地址和端口
? ? ? ? proxy_set_header Host minio-server-endpoint; # 根據需要調整
? ? ? ? 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;
? ? }
}
2. 負載均衡
Nginx 支持多種負載均衡算法(如輪詢、最少連接、哈希等)來分配請求到多個后端服務器。
upstream backend_servers {
? ? server backend1.example.com weight=3;
? ? server backend2.example.com;
? ? server backend3.example.com;
}server {
? ? listen 80;
? ? server_name example.com;? ? location / {
? ? ? ? proxy_pass http://backend_servers;
? ? }
}
3. 緩存
可以配置 Nginx 來緩存靜態內容或動態響應,以減少對后端服務器的壓力。
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;server {
? ? location / {
? ? ? ? proxy_cache my_cache;
? ? ? ? proxy_pass http://backend;
? ? }
}
4. SSL/TLS 加密
為網站啟用 HTTPS 支持,確保數據傳輸的安全性。
server {
? ? listen 443 ssl;
? ? server_name example.com;? ? ssl_certificate /etc/nginx/ssl/example.com.crt;
? ? ssl_certificate_key /etc/nginx/ssl/example.com.key;? ? location / {
? ? ? ? proxy_pass http://backend;
? ? }
}
5. 靜態文件服務
直接從本地文件系統提供靜態文件服務。
server {
? ? listen 80;
? ? server_name example.com;? ? location /static/ {
? ? ? ? alias /var/www/static/;
? ? }
}
6. URL 重寫與重定向
使用 rewrite 指令實現 URL 的重寫或重定向。
server {
? ? listen 80;
? ? server_name old.example.com;? ? rewrite ^/(.*)$ http://new.example.com/$1 permanent;
}
7. 訪問控制
基于 IP 地址或其他條件限制訪問。
location /admin/ {
? ? allow 192.168.1.0/24; # 允許特定網段
? ? deny all; ? ? ? ? ? ? # 拒絕所有其他來源
}
8. Gzip 壓縮
啟用 Gzip 壓縮以減少傳輸的數據量。
gzip on;
gzip_types text/plain application/xml;
gzip_proxied any;
gzip_min_length 1000;
9. 日志管理
配置訪問日志和錯誤日志的位置及格式。
access_log /var/log/nginx/access.log combined;
error_log /var/log/nginx/error.log warn;
10. 狀態監控
啟用 Nginx 的狀態頁面以便于監控性能和健康狀況。
location /nginx_status {
? ? stub_status on;
? ? access_log off;
? ? allow 127.0.0.1; # 僅允許本地訪問
? ? deny all;
}?
補充: