美文网首页
nginx配置文件详解

nginx配置文件详解

作者: wangcc_sd | 来源:发表于2019-03-08 14:53 被阅读0次

    nginx.conf 通用配置

    user www-data;  # 运行 nginx 的所属组和所有者
    worker_processes 1;  # 开启一个 nginx 工作进程,一般 CPU 几核就写几
    pid /run/nginx.pid;  # pid 路径
    
    events {
        worker_connections 768;  # 一个进程能同时处理 768 个请求
        # multi_accept on;
    }
    
    # 与提供 http 服务相关的配置参数,一般默认配置就可以,主要配置在于 http 上下文里的 server 上下文
    http {
        ##
        # Basic Settings
        ##
    
        ... 此处省略通用默认配置
    
        ##
        # Logging Settings
        ##
        ... 此处省略通用默认配置
    
        ##
        # Gzip Settings
        ##
    
        ... 此处省略通用默认配置
    
        ##
        # nginx-naxsi config
        ##
    
        ... 此处省略通用默认配置
    
        ##
        # nginx-passenger config
        ##
    
        ... 此处省略通用默认配置
    
        ##
        # Virtual Host Configs
        ##
    
        ... 此处省略通用默认配置
    
        # 此时,在此添加 server 上下文,开始配置一个域名,一个 server 配置段一般对应一个域名
        server {
            listen 80;        # 监听本机所有 ip 上的 80 端口
            server_name _;      # 域名:www.example.com 这里 "_" 代表获取匹配所有
            root /home/filename/;  # 站点根目录
    
            location / {       # 可有多个 location 用于配置路由地址
                try_files index.html =404;
            }
    }
    
    # 邮箱的配置,因为用不到,所以把这个 mail 上下文给注释掉
    #mail {
    #    # See sample authentication script at:
    #    # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
    #    
    #    # auth_http localhost/auth.php;
    #    # pop3_capabilities "TOP" "USER";
    #    # imap_capabilities "IMAP4rev1" "UIDPLUS";
    #   
    #    server {
    #        listen   localhost:110;
    #        protocol  pop3;
    #        proxy    on;
    #    }
    #
    #    server {
    #        listen   localhost:143;
    #        protocol  imap;
    #        proxy    on;
    #    }
    #}
    

    server 配置

    server {
        listen 80;        # 监听本机所有 ip 上的 80 端口
        server_name _;      # 域名:www.example.com 这里 "_" 代表获取匹配所有
        root /home/filename/;  # 站点根目录
    
        location / {       # 可有多个 location 用于配置路由地址
          try_files index.html =404;
        }
    }
    

    这里的 root 字段最好写在 location 字段的外边,防止出现无法加载 css、js 的情况。因为 css、js 的加载并不是自动的,nginx 无法执行,需要额外的配置来返回资源,所以,对于静态页面的部署,这样做是最为方便的。

    这里对 root 作进一步解释,例如在服务器上有 /home/zhihu/ 目录,其下有 index.html 文件和 css/ 以及 img/ , root /home/zhihu/; 就将指定服务器加载资源时是在 /home/zhihu/ 下查找。
    其次, location 后的匹配分多种,其各类匹配方式优先级也各不相同。这里列举一精确匹配例子:

    server {
        listen 80;        
        server_name _;      
        root /home/zhihu/;  
    
        location = /zhihu {
          rewrite ^/.* / break;
          try_files index.html =404;
        }
    }
    

    此时,访问 www.example.com/zhihu 就会加载 zhihu.html 出来了。由于 location 的精确匹配,只有访问 www.example.com/zhihu 这个路由时才会正确响应,而且此时要通过 rewrite 正则匹配,把 /zhihu 解析替换成原来的 / 。

    相关文章

      网友评论

          本文标题:nginx配置文件详解

          本文链接:https://www.haomeiwen.com/subject/bmurpqtx.html