Nginx 常用配置

104 阅读1分钟
  1. 配置静态文件访问:
location /static/ {
    alias /path/to/static/files/;
}

  1. 配置反向代理:
location /api/ {
    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;
}

  1. 配置负载均衡:
http {
    upstream backend_servers {
        server backend1.example.com;
        server backend2.example.com;
    }

    server {
        location / {
            proxy_pass http://backend_servers;
        }
    }
}

  1. 配置HTTPS:
server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /path/to/ssl/certificate.crt;
    ssl_certificate_key /path/to/ssl/certificate.key;

    location / {
        root /path/to/website/files;
    }
}

  1. 配置缓存:
http {
    proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m;

    server {
        location / {
            proxy_cache my_cache;
            proxy_pass http://backend_server;
            proxy_cache_valid 200 1h;
            proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
        }
    }
}