Nginx 是一款高性能的开源 Web 服务器,也可用作反向代理服务器。以下是一些常用的 Nginx 配置示例:
Bash
server {
listen 80;
server_name example.com;
location / {
root /path/to/your/static/files;
index index.html index.htm;
}
}
2. 反向代理
Bash
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://your_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;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
3. 负载均衡
http {
upstream backend {
server backend1.example.com;
server backend2.example.com;
server backend3.example.com;
}
server {
listen 80;
server_name example.com;
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;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
}
4. SSL/TLS 配置
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/your/certificate.crt;
ssl_certificate_key /path/to/your/private.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384';
location / {
root /path/to/your/static/files;
index index.html index.htm;
}
}
5. Basic 认证
server {
listen 80;
server_name example.com;
location / {
auth_basic "Restricted Access";
auth_basic_user_file /path/to/.htpasswd;
root /path/to/your/static/files;
index index.html index.htm;
}
}
6. URL 重写
server {
listen 80;
server_name example.com;
location /old {
rewrite ^/old/(.*)$ /new/$1 permanent;
}
location /new {
root /path/to/your/new/files;
index index.html index.htm;
}
}
7. 防止目录遍历
location / {
root /path/to/your/static/files;
index index.html index.htm;
location ~ ^/(.+)/ {
deny all;
}
}
8. 限制访问频率
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
server {
# ...
location / {
limit_req zone=one burst=5;
root /path/to/your/static/files;
index index.html index.htm;
}
}
9. Gzip 压缩
server {
# ...
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
}
10. 设置缓存
server {
# ...
location / {
proxy_cache my_cache;
proxy_cache_valid 200 304 1h;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_ignore_headers Cache-Control Expires;
add_header X-Cache-Status $upstream_cache_status;
}
}
本文暂时没有评论,来添加一个吧(●'◡'●)