Nginx Security Hardening là quá trình giảm attack surface và cấu hình Nginx theo đúng vai trò: chỉ listen interface/port cần thiết, phục vụ đúng document root, không lộ file nhạy cảm, proxy/FastCGI đúng boundary, dùng TLS hiện đại, giới hạn request hợp lý và luôn validate config trước reload. Hardening không thay patching hay application security.
Tài liệu Nginx mô tả master process đọc cấu hình và worker xử lý request; thay đổi cấu hình có thể được reload gracefully. Điều này giúp vận hành an toàn hơn nếu workflow luôn là backup → nginx -t → reload → read-back → functional test.
Inventory, exposure và filesystem serving boundary
1. Inventory build, module và config source
Trước khi sửa, xác định Nginx đến từ distro package hay repository khác, version/package còn support và module nào được build/load. Không xem việc “ẩn version” là thay thế patching. Nếu package/security-update state chưa rõ, xử lý theo Linux Patch Management trước khi coi Nginx hardening là hoàn tất.
nginx -V
nginx -T > /tmp/nginx-effective.conf
nginx -T giúp xem effective configuration gồm các file include. Snapshot này hữu ích để review và rollback, nhưng có thể chứa path/hostname nhạy cảm nên phải bảo vệ.
2. Chỉ listen đúng interface và port
Kiểm tra listen và socket thực tế:
sudo ss -lntup | grep nginx
Nếu Nginx chỉ là origin sau load balancer/CDN, architecture có thể không cần public origin access từ mọi IP. Network restriction phải được xử lý cùng host/cloud firewall, không chỉ trong Nginx.
3. Server block mặc định không nên phục vụ nội dung ngoài ý muốn
Nginx chọn server block dựa trên listen/server_name. Một default server cấu hình lỏng có thể phục vụ request Host không mong muốn. Với HTTPS hiện đại, có thể thiết kế default virtual host không phục vụ application; Nginx có ssl_reject_handshake cho use case phù hợp.
Không copy cấu hình reject vào production nếu đang có monitoring, health check hoặc multi-tenant dependency dựa vào default server.
4. Document root và alias phải tối thiểu
root và alias xác định filesystem path Nginx có thể phục vụ. Không đặt root quá cao như /var/www nếu chỉ cần một release directory cụ thể. Review alias/location cẩn thận để tránh expose path không intended.
5. Directory listing
Module autoindex tạo directory listing khi bật. Tài liệu Nginx cho biết autoindex mặc định là off. Chỉ bật khi business requirement rõ:
autoindex off;
Đừng coi đây là control duy nhất: nếu file nhạy cảm có URL đoán được, tắt listing không ngăn direct request.
6. Chặn file nhạy cảm theo application model
Web root có thể chứa file deploy, VCS metadata, environment hoặc backup ngoài ý muốn. Có thể dùng location rules để deny pattern đã xác minh, nhưng tốt hơn là không đưa secret/backup vào public document root ngay từ đầu.
Ví dụ định hướng:
location ~ /\. {
deny all;
}
Pattern dotfile có exception hợp lệ như ACME /.well-known/; vì vậy rule phải được thiết kế theo app và test trước rollout.
7. server_tokens chỉ là information-reduction control
server_tokens off; có thể giảm version information trong một số response/error page, nhưng không vá vulnerability. Priority vẫn là supported package + security update.
TLS, headers và request controls
8. TLS: dùng defaults hiện đại và hiểu termination point
Tài liệu Nginx hiện mặc định ssl_protocols TLSv1.2 TLSv1.3. Nếu Nginx terminate TLS, cần quản certificate/private key, protocol, session và renewal lifecycle. Private key phải có filesystem access hạn chế nhưng Nginx master vẫn cần đọc được.
ssl_protocols TLSv1.2 TLSv1.3;
Không copy cipher list cũ từ blog. Defaults và OpenSSL behavior thay đổi theo version. Nếu TLS terminate ở CDN/load balancer, origin TLS policy là một trust boundary riêng.
9. Security headers cần khớp application
Nginx có thể thêm headers như HSTS, X-Content-Type-Options hoặc Content-Security-Policy, nhưng header security không nên triển khai theo template mù. HSTS có ảnh hưởng dài hạn tới HTTPS behavior; CSP có thể làm hỏng script/style nếu policy không được test.
Dùng report-only/staging khi phù hợp và biết lớp nào là source of truth: app, Nginx hay CDN/WAF.
10. Request size và timeout
Giới hạn request có thể giảm abuse và bảo vệ backend, nhưng phải dựa trên use case. Ví dụ upload application cần client_max_body_size lớn hơn site chỉ nhận form text. Timeout quá thấp tạo false positive; quá cao có thể làm giữ resource.
Đặt limit theo endpoint/application need, không theo “giá trị hardening chuẩn”.
11. Rate limiting không phải DDoS protection hoàn chỉnh
Nginx hỗ trợ request/connection limiting. Nó hữu ích với endpoint nhạy cảm hoặc abuse đơn giản, nhưng origin-level rate limit không chống được volumetric DDoS nếu network uplink đã bão hòa.
Rate limit cần đo false positive, đặc biệt khi nhiều user đi qua NAT/proxy. Nếu dùng CDN/reverse proxy, phải xử lý real client IP đúng trước khi limit theo địa chỉ.
Proxy, runtime, logging và reload validation
12. Reverse proxy: chỉ trust proxy headers từ nguồn đúng
Không tin X-Forwarded-For từ mọi client. Nếu origin sau trusted proxy, cấu hình real-IP phải giới hạn trusted proxy network. Sai trust chain có thể làm log/rate-limit/access-control dựa trên IP trở nên vô nghĩa.
13. FastCGI/PHP boundary
Nginx thường chuyển PHP request sang PHP-FPM. Security phụ thuộc cả location matching, script path mapping và FPM pool. Không nên để arbitrary filename bị chuyển sang interpreter chỉ vì URI kết thúc giống PHP nếu filesystem/application model không cho phép.
Phần process isolation, pool user, socket/TCP exposure và FPM environment thuộc PHP-FPM Security; Nginx chỉ nên forward đúng request intended và giữ boundary giữa web server với runtime rõ ràng.
14. Method restriction và access control
Nginx có limit_except và access modules, nhưng method restriction phải dựa trên API/application contract. Chặn PUT/DELETE ở Nginx trong khi application cần chúng sẽ gây outage; ngược lại app không dùng method đó thì giảm exposure có thể hợp lý.
15. Logging đủ để điều tra
Access/error log cần chứa timestamp, request path, status, upstream timing và client identity phù hợp trust chain. Không log secret, Authorization header hoặc sensitive query data chỉ để “đủ evidence”. Nếu cần thiết kế event, retention và mối liên hệ giữa web logs với privileged/config changes ở cấp server, xem Server Audit Logging.
Log rotation/retention phải được quản lý; disk đầy vì log cũng là availability risk.
16. Permission của config, certificate và web root
Nginx worker không nên có quyền ghi toàn bộ application source. Certificate private key và config nhạy cảm chỉ nên đọc bởi identity cần thiết. Xem File Permission & Ownership trên Web Server để thiết kế owner/write path.
17. Config test và graceful reload
Trước mọi reload:
sudo nginx -t
Nếu PASS, dùng cơ chế graceful reload theo distro/service manager. Tài liệu Nginx hỗ trợ signal reload; khi reload, master kiểm tra config mới và worker cũ có thể hoàn tất request hiện tại.
Sau reload, không dừng ở “syntax OK”. Kiểm tra process, socket, response và upstream/application behavior.
Mẫu Nginx Hardening Review Record
Đây là template evidence, không phải cấu hình Nginx thực tế của SecureWebOps.
| Control | Observed | Expected | Evidence | Result |
|---|---|---|---|---|
| Package/version | Observed package | Supported/patched | Package source + advisory | PASS/FAIL |
| Listen | Socket/interface | Intended only | ss + config |
PASS/FAIL |
| Document root | Observed | Minimal intended path | nginx -T |
PASS/FAIL |
| TLS | Observed termination/protocol | Current policy | Config + handshake test | PASS/FAIL |
| Logs | Access/error | Usable evidence | Log sample | PASS/FAIL |
Checklist Nginx Security Hardening
- Package/source/version có owner và còn support.
nginx -Tđược snapshot trước change.- Listen interface/port đúng architecture.
- Default server không phục vụ app ngoài ý muốn.
- Document root/alias tối thiểu.
- Autoindex chỉ bật khi cần.
- Secret/backup không nằm trong public root.
- TLS termination/protocol được xác minh.
- Security headers có owner và test.
- Request size/timeout theo use case.
- Rate limit không dựa trên spoofed client IP.
- Trusted proxy/real-IP được khóa đúng source.
- FastCGI mapping chỉ forward request intended.
- Config/certificate permission phù hợp.
nginx -tPASS trước reload.- Functional test sau reload.
Nguồn kỹ thuật tham khảo
Kết luận
Nginx hardening tốt không phải một file config “security.conf” copy từ Internet. Nó là việc giảm exposure theo kiến trúc thật, bảo vệ filesystem/proxy boundary, dùng TLS hiện đại, đặt limit có lý do và luôn kiểm chứng effective configuration.
Workflow an toàn là snapshot → chỉnh nhỏ → nginx -t → graceful reload → read-back → functional test. Nếu config hợp lệ nhưng route, upload, API hoặc upstream hỏng thì hardening vẫn chưa PASS.
