Đến nội dung chính
sang.id.vn
Quay lại

Ghi chú NGINX — Những thứ mình hay dùng lại

English

Mấy thủ thuật NGINX mình hay dùng đi dùng lại. NGINX về cơ bản là một ngôn ngữ cấu hình — nó chạy theo độ ưu tiên của directive, không phải từ trên xuống dưới.

Rewrite với last

Dùng rewrite kèm last để dừng chuỗi rewrite hiện tại và bắt đầu request nội bộ mới với URL đã rewrite:

if ($allow != 1) {
    rewrite ^ /__auth_beta$uri last;
}

auth_request chạy trước try_files

auth_request chạy trước try_files. Vì try_files nhận được named location, ta có thể dùng location dự phòng khi các directive trước đó không rewrite:

location /__auth_beta {
    internal;
    auth_request /api/beta/verify-invitation-code;
    error_page 401 @coming_soon;
    try_files /index.html =404;
}

location @auth_success {
    set $allow 1;
    rewrite ^ $request_uri last;
}

Biến điều kiện với map

map tạo biến dựa trên điều kiện. Tiện cho việc đặt cờ:

map $http_user_agent $is_bot {
    default 0;
    ~*bot 1;
}

server {
    if ($is_bot) {
        return 403;
    }
}

Giới hạn request

limit_req chống lạm dụng:

http {
    limit_req_zone $binary_remote_addr zone=mylimit:10m rate=1r/s;

    server {
        location / {
            limit_req zone=mylimit burst=5 nodelay;
            proxy_pass http://backend;
        }
    }
}

Rule theo vùng địa lý

geo gán biến theo IP client. Tiện cho việc chặn theo vùng:

geo $country {
    default ZZ;
    127.0.0.1 US;
    192.168.1.0/24 RU;
}

server {
    if ($country = RU) {
        return 403;
    }
}

Load balancing

upstream phân phối request qua nhiều backend:

upstream backend {
    server backend1.example.com;
    server backend2.example.com;
}

server {
    location / {
        proxy_pass http://backend;
    }
}

Custom log format

log_format custom '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

server {
    access_log /var/log/nginx/access.log custom;
}

DNS resolver cho dynamic upstream

Nếu proxy tới domain name, NGINX resolve lúc load config và cache IP. Với dynamic upstream, cần set resolver:

http {
    resolver 8.8.8.8 8.8.4.4;

    server {
        location / {
            proxy_pass http://example.com;
        }
    }
}

Share this post on:

Bài trước
Cách mình tối ưu tính năng tự động xếp lịch
Bài tiếp
Config MySQL để full-text search tiếng Việt chuẩn chỉnh