Nginx 是一個高性能的 HTTP 服務器和反向代理服務器,廣泛應用于負載均衡和 URL 重寫等場景。以下是關于 Nginx 負載均衡和 URL 重寫的基本信息和示例。
Nginx 支持多種負載均衡方法,包括輪詢、最少連接、IP 哈希等。以下是一個簡單的配置示例:
http {
upstream backend {
# 定義后端服務器
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}
server {
listen 80;
location / {
# 使用負載均衡
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
在這個例子中,Nginx 會在 backend1.example.com、backend2.example.com 和 backend3.example.com 三臺后端服務器之間進行輪詢。
Nginx 提供了強大的 URL 重寫功能,可以通過 rewrite 指令來實現 URL 的重定向和重寫。以下是一些示例:
server {
listen 80;
server_name example.com;
# 將 /old-path 重定向到 /new-path
rewrite ^/old-path$ /new-path permanent;
}
server {
listen 80;
server_name example.com;
# 將所有以 .html 結尾的請求重寫為 .php
rewrite ^/(.*)\.html$ /$1.php last;
}
server {
listen 80;
server_name example.com;
location / {
# 如果請求的文件不存在,則重寫到 /index.php
try_files $uri $uri/ /index.php?$args;
}
}
Nginx 的負載均衡和 URL 重寫功能非常強大,可以根據不同的需求進行靈活配置。在實際應用中,可以根據具體的業務需求調整配置,確保性能和可用性。請確保在配置 Nginx 之前備份原有的配置文件,并在更改后進行測試。