Nginx 配置文件示例:虚拟主机、gzip 压缩、反向代理

Nginx 是一个高性能的 HTTP 和反向代理服务器,它不支持 .htaccess 文件,而是使用 nginx.conf 配置文件进行配置。以下是一个示例的 nginx.conf 配置文件:

# 设置工作进程数,一般设置为 CPU 核心数的 2 倍
worker_processes 2;

# 设置错误日志路径
error_log /var/log/nginx/error.log;

# 设置访问日志路径和格式
access_log /var/log/nginx/access.log combined;

# 设置事件模块
events {
    # 设置最大连接数
    worker_connections 1024;
}

http {
    # 设置 MIME 类型
    include /etc/nginx/mime.types;

    # 设置默认文件类型
    default_type application/octet-stream;

    # 设置日志格式
    log_format main '$remote_addr - $remote_user [$time_local] '"$request"'
                  '$status $body_bytes_sent '"$http_referer"'
                  '"$http_user_agent" '"$http_x_forwarded_for"';

    # 设置访问日志
    access_log /var/log/nginx/access.log main;

    # 设置 gzip 压缩
    gzip on;
    gzip_disable 'msie6';
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    # 设置虚拟主机
    server {
        # 设置监听端口
        listen 80;

        # 设置域名
        server_name example.com;

        # 设置根目录
        root /var/www/example.com;

        # 设置默认文件
        index index.html;

        # 设置访问限制
        location / {
            allow 192.168.1.0/24;
            deny all;
        }

        # 设置反向代理
        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;
        }
    }
}

上述示例中,配置了一个监听 80 端口的虚拟主机,使用了 gzip 压缩和访问限制。同时,还配置了一个反向代理,将所有以 /api/ 开头的请求转发到后端服务器。请根据实际需求修改配置文件中的域名、根目录、反向代理等参数。

Nginx 配置文件示例:虚拟主机、gzip 压缩、反向代理

原文地址: https://www.cveoy.top/t/topic/fAJW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录