nginx 配置文件示例

nginx 配置文件详解示例
2023-07-19 20:53:55 0
本文 1564 个字,阅读需要大约 4 分钟

文章目录 [回顶部]
[--评论--]
# 全局配置
user nginx;
worker_processes auto;
pid /run/nginx.pid;
error_log /var/log/nginx/error.log;

# 配置事件模块
events {
    worker_connections 1024;
    multi_accept on;
    use epoll;
}

# 配置HTTP模块
http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    access_log /var/log/nginx/access.log combined;
    error_log /var/log/nginx/error.log;

    # 配置服务器块
    server {
        listen 80;
        server_name example.com;

        # 配置SSL
        listen 443 ssl;
        ssl_certificate /path/to/certificate.crt;
        ssl_certificate_key /path/to/private.key;

        # 配置根目录
        root /var/www/html;
        index index.html index.htm;

        # 配置重定向
        location / {
            try_files $uri $uri/ /index.html;
        }

        # 配置反向代理
        location /api {
            proxy_pass http://backend_server;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }

        # 配置缓存
        location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
            expires 1d;
            add_header Cache-Control "public";
        }

        # 配置Gzip压缩
        gzip on;
        gzip_comp_level 5;
        gzip_min_length 256;
        gzip_proxied any;
        gzip_types application/javascript application/json text/css;

        # 配置限制连接频率
        limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

        # 配置防止恶意请求
        limit_conn_zone $binary_remote_addr zone=addr:10m;

        # 配置安全头部
        add_header X-Frame-Options "SAMEORIGIN";
        add_header X-Content-Type-Options "nosniff";
        add_header X-XSS-Protection "1; mode=block";

        # 处理错误页面
        error_page 404 /404.html;
        error_page 500 502 503 504 /50x.html;
        
        location = /50x.html {
            root /usr/share/nginx/html;
        }
    }
}

在上述示例中,除了之前提到的配置,还包含了以下详细解释:

  • worker_processes auto; 指令设置Nginx工作进程的数量自动化,根据系统资源动态分配。
  • multi_accept on; 允许每个工作进程同时接受多个连接。
  • use epoll; 使用epoll事件模型来处理连接,以提高性能。
  • access_log /var/log/nginx/access.log combined; 配置访问日志格式为combined,将访问日志记录到指定文件中。
  • listen 443 ssl; 配置HTTPS监听,并启用SSL加密。
  • ssl_certificatessl_certificate_key 指令分别指定SSL证书和私钥的路径。
  • index 指令设置默认的索引文件。
  • try_files 指令配置URL重定向,尝试查找请求的文件,如果找不到则重定向到/index.html。
  • gzip 相关指令配置Gzip压缩,对指定类型的文件进行压缩。
  • limit_req_zonelimit_conn_zone 指令设置连接频率限制和防止恶意请求的限制。
  • add_header 指令添加安全头部,提供额外的安全性和防护。
  • error_page 指令配置特定错误页面的处理。
    这只是一个示例配置文件,你可以根据自己的需求进行调整和扩展。请注意,对于使用HTTPS和SSL的配置,你需要将证书和私钥的路径替换为你自己的有效证书和私钥路径。
原创文章,转载请注明出处~ 以上就是本文的全部内容啦,有什么疑问欢迎在下方评论区留言嗷,收到通知会及时回复~
文章浏览总量:517 (非即时 )
Comments
Nothing...
推荐文章 使用余弦向量算法进行推荐(分数)
跳转到顶部