NGINX là gì?
NGINX được phát triển bởi kỹ sư người Nga Igor Sysoev vào năm 2002 và ra mắt công chúng năm 2004, nhằm giải quyết bài toán C10k - xử lý 10.000 kết nối đồng thời. Với kiến trúc hướng sự kiện (event-driven) đơn luồng, NGINX nhanh chóng phổ biến nhờ hiệu suất cao, ít tốn tài nguyên và khả năng làm reverse proxy, load balancer.
Kestrel là gì?
Kestrel là một máy chủ web được tích hợp trong .NET và ASP.NET Core, đóng vai trò là một máy chủ HTTP nhanh chóng, hiệu quả, và có khả năng chịu tải cao cho các ứng dụng .NET. Được giới thiệu lần đầu tiên cùng với .NET Core, nó nhanh chóng trở thành lựa chọn phổ biến nhờ vào hiệu năng vượt trội, cấu trúc gọn nhẹ và tính năng bảo mật.
Phân biệt:
- Kestrel: Được gọi là Internal Web Server hoặc Application Server. Đây là máy chủ web mặc định được tích hợp sẵn vào ứng dụng ASP.NET Core. Nhiệm vụ chính của nó là xử lý các logic lập trình .NET và tạo ra phản hồi (response).
- NGINX: Được gọi là Reverse Proxy Server (hoặc Edge Web Server). Nó đóng vai trò là "cổng vào" duy nhất cho toàn bộ hệ thống, đứng chắn trước một hoặc nhiều Application Server (như Kestrel, Tomcat, Gunicorn, PHP-FPM).
Cài đặt Nginx trên Windows
Bước 1: Tải Nginx cho Windows
Truy cập trang chính thức: https://nginx.org/en/download.html
Khuyến nghị tải Stable version (ví dụ: nginx-1.30.0) hoặc Mainline.
Tải file .zip (nginx/Windows-1.xx.x.zip).
Bước 2: Giải nén và thiết lập thư mục
Giải nén vào thư mục ví dụ: D:\nginxCấu trúc thư mục sẽ như sau:
D:\nginx
├── conf
├── html
├── logs
├── nginx.exe
└── ...
Bước 3: Test Nginx ban đầu
Mở Command Prompt hoặc PowerShell với quyền Administrator, chạy lệnh:
cd D:\nginx
start nginx
Kiểm tra Nginx đang chạy:
tasklist /fi "imagename eq nginx.exe"
Kết quả
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
nginx.exe 12420 Console 11 10,484 K
nginx.exe 35412 Console 11 10,232 K
Truy cập trình duyệt: http://localhost → Nếu thấy trang welcome của Nginx là thành công.
Welcome to nginx!
If you see this page, nginx is successfully installed and working. Further configuration is required for the web server, reverse proxy, API gateway, load balancer, content cache, or other features.
...
Các lệnh trên Windows
nginx -s stop # Dừng Nginx
nginx -s quit # Thoát graceful
nginx -s reload # Reload config (rất quan trọng)
nginx -t # Kiểm tra cấu hình có lỗi khôngNhững thư mục và câu lệnh quan trọng
File và thư mục
/etc/nginx
Thư mục /etc/nginx là thư mục gốc để cài đặt cấu hình mặc định cho NGINX. Trong thư mục này, bạn sẽ tìm thấy những file config mô tả cách NGINX hoạt động.
/etc/nginx/nginx.conf
Đây là file config mặc định của NGINX. File config này sẽ thiết lập global những thứ như worker process, tuning, logging, load module hay reference đến những file config khác. Mặc định, /etc/nginx/nginx.conf chứa block cấp cao nhất - http - cái mà sẽ thêm những file config khác ở trong thư mục dưới dây.
/etc/nginx/conf.d/
Đây là thư mục chứa những file config mặc định dùng HTTP. Những file có đuôi .conf sẽ được thêm vào trong file /etc/nginx/nginx.conf. Ở một số phiên bản khác, folder này được đặt tên là sites-enablenhưng quy ước này đã bị loại bỏ.
/var/log/nginx/
Đây là thư mục log mặc định của NGINX. Trong thư mục này, bạn sẽ tìm thấy access.log và error.log. File access.log chứa thông tin của mỗi request đến NGINX server. File error.log chứa lỗi và những thông tin debug.
Cấu trúc cơ bản của nginx\conf\nginx.conf
File này được chia thành các khối (block) lồng nhau theo phân cấp. Mỗi khối đại diện cho một phạm vi cấu hình cụ thể:
- Global Block: Nằm ở ngoài cùng. Chứa các thiết lập chung cho toàn bộ server như worker_processes (số lượng tiến trình xử lý).Events Block: Thiết lập cách Nginx xử lý các kết nối (ví dụ: worker_connections).
- Http Block: Đây là nơi bạn sẽ dành 90% thời gian ở đây. Nó chứa các thiết lập về giao thức HTTP, bảo mật, nén dữ liệu và định nghĩa các Server (website).
- Server Block: Định nghĩa một Virtual Host (một tên miền hoặc một cổng cụ thể).
- Location Block: Định nghĩa cách xử lý các đường dẫn URL cụ thể (ví dụ: /api, /images, hoặc /).
Serving Static Content
Trước tiên, chúng ta hãy xem nội dung file nginx.config
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name localhost;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
Bạn chú ý dòng
server {
listen 80;
server_name localhost;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
Nếu bạn cài đặt Nginx tại D:\nginx, thì đường dẫn đầy đủ của root html sẽ là:
D:\nginx\html\Nginx mặc định hiểu rằng các đường dẫn không bắt đầu bằng ký tự ổ đĩa (như C:\) sẽ được tính từ thư mục chạy chương trình (thư mục chứa file nginx.exe).
Tuy nhiên, khi làm việc với .NET / Blazor Server, dòng này thường được thay đổi hoặc thay thế hoàn toàn:
Nếu bạn host file tĩnh (Blazor WebAssembly): Bạn sẽ đổi html thành đường dẫn chứa các file đã publish của mình.
Ví dụ: root D:/data/publish/wwwroot;
Nếu bạn chạy Blazor Server (SignalR): Bạn thường xóa bỏ dòng root và index bên trong location /, thay thế bằng proxy_pass để đẩy yêu cầu sang Kestrel.
Ở đây, mình chỉ tạo 1 trang HTML tĩnh:<!doctype html>
<html lang="en">
<head>
<title>Title</title>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.8/css/bootstrap.min.css" integrity="sha512-2bBQCjcnw658Lho4nlXJcc6WkV/UxpE/sAokbXPxQNGqmNdQrWqtw26Ns9kFF/yG792pKR1Sx8/Y1Lf1XN4GKA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<header>
<!-- place navbar here -->
</header>
<main></main>
<footer>
<!-- place footer here -->
</footer>
<!-- Bootstrap JavaScript Libraries -->
<script
src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js"
integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r"
crossorigin="anonymous"
></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.8/js/bootstrap.min.js" integrity="sha512-nKXmKvJyiGQy343jatQlzDprflyB5c+tKCzGP3Uq67v+lmzfnZUi/ZT+fc6ITZfSC5HhaBKUIvr/nTLCV+7F+Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</body>
</html>
Thêm nội dung sau vào tag main:
<main>
<div class="jumbotron text-center">
<h1>My First Bootstrap Page</h1>
<p>Resize this responsive page to see the effect!</p>
</div>
<div class="container">
<div class="row">
<div class="col-sm-4">
<h3>Column 1</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
</div>
<div class="col-sm-4">
<h3>Column 2</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
</div>
<div class="col-sm-4">
<h3>Column 3</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
</div>
</div>
</div>
</main>
Truy cập http://localhost/demo.html để xem kết quả
Stop NGINX
Dùng lệnh stop để dừng NGINX.\nginx -s stop
Nhận xét
Đăng nhận xét