Nginx 是一个高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3/SMTP 代理服务器。以下是一些基本的 Nginx 配置示例,涵盖从入门到精通的一些常见场景。
- 基本的服务器配置:
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
- 配置反向代理:
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://backend_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;
}
}
- 配置负载均衡:
upstream backend {
server backend1.example.com;
server backend2.example.com;
}
server {
listen 80;
server_name localhost;
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;
}
}
- 配置 SSL/TLS 证书:
server {
listen 443 ssl;
server_name localhost;
ssl_certificate /etc/nginx/ssl/nginx.crt;
ssl_certificate_key /etc/nginx/ssl/nginx.key;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
- 配置静态文件缓存:
server {
listen 80;
server_name localhost;
location ~* \.(jpg|jpeg|png|css|js|ico|html)$ {
expires 30d;
}
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
- 配置重写规则:
server {
listen 80;
server_name localhost;
rewrite ^/oldpage$ /newpage permanent;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
这些示例展示了 Nginx 的基本配置,包括服务器定义、反向代理、负载均衡、SSL/TLS 配置、静态文件缓存和 URL 重写规则。这些是学习 Nginx 的基础,随着深入学习,你可能还需要了解如何进行高级配置,如速率限制、请求限制、防火墙设置等。