内容纲要

🗂 | 本文目录: NGINX 指南


NGINX 及其模块的工作方式由配置文件决定。

NGINX 配置文件语法规则

  1. 配置文件由指令与指令块构成;
  2. 每条指定以分号(;)结尾,指令与参数间以空格符号分割;
  3. 指令块以大括号({ })将多条指令组织在一起;
  4. include 语句允许组合多个配置文件以提升可维护性;
  5. 使用 # 符号添加注释;
  6. 使用 $ 符号使用变量;
  7. 部分指令参数支持正则表达式;

配置文件及目录

nginx.conf 文件是 NGINX 服务使用的默认配置入口。这个配置文件为诸如 worker 进程、调优、日志、加载动态模块以及对其他 NGINX 配置文件的引用等设置了全局设置。在默认配置中,nginx.conf 文件包括顶层的 http 块,或者说上下文,其中包括接下来描述的目录中的所有配置文件。

该文件位于 /usr/local/nginx/conf/etc/nginx/usr/local/etc/nginx 目录下,这个目录是 NGINX 服务器的默认配置根目录。

如果不知道 NGINX 的配置文件路径可以使用

$ sudo nginx -t

如果你是通过编译安装会得到返回:

nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

如果你是通过包管理安装会得到返回:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

(如果通过包管理安装)在 /etc/nginx/conf.d 目录中包含了默认的 HTTP 服务器配置文件(编译安装没有这个配置及目录)。这个目录中以 .conf 结尾的文件会被包含在 /etc/nginx/nginx.conf 文件的顶层 http 块中。在一些软件包库中,这个文件夹(conf.d)被命名为 sites-enabled,而配置文件则从一个名为 sites-available 的文件夹中链接出来,不过这个惯例已经被废弃了。

利用 include 语句并以这种方式组织你的配置而不是直接修改 nginx.conf 文件,以保持配置文件的简洁是最好的做法。

下面是通过编译安装、Debian 或 Ubuntu 通过 APT 安装和 CentOS 通过 DNF 安装的默认配置,默认配置文件大体上相同。

不同安装方式的默认配置文件差异

编译安装

通过编译安装的 NGINX 默认的 nginx.conf 配置文件内容(位于 /usr/local/nginx/conf):

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

Debian/Ubuntu 通过 APT 安装

Debian / Ubuntu 通过 apt install nginx-full 安装的 NGINX 默认的 nginx.conf 配置文件内容(位于 /etc/nginx):

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # SSL Settings
    ##

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
    ssl_prefer_server_ciphers on;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;

    # gzip_vary on;
    # gzip_proxied any;
    # gzip_comp_level 6;
    # gzip_buffers 16 8k;
    # gzip_http_version 1.1;
    # gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

#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;
#   }
#}

CentOS 通过 DNF 安装

CentOS 通过 dnf install nginx 安装的 NGINX 默认的 nginx.conf 配置文件内容(位于 /etc/nginx):

# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    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;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2 default_server;
#        listen       [::]:443 ssl http2 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers PROFILE=SYSTEM;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        location / {
#        }
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}

前面提到 http {} 块中的 include 语句用来组织模块化配置,在上述示例中,编译中默认没有明确配置,而在 Debian / Ubuntu 中是 /etc/nginx/conf.d/*.conf/etc/nginx/sites-enabled/*,在如 CentOS 中是 /etc/nginx/conf.d/*.conf

这部分它所包含的目录作用在于,当管理多个站点(也就是虚拟主机)时,可以将每个站点写成独立的虚拟主机配置文件,而不是将多个站点直接写在 nginx.conf 中,这样有助于维护,保持了配置文件的简洁。

如前文和示例所述,Debian / Ubuntu 默认配置了 /etc/nginx/conf.d/*.conf/etc/nginx/sites-enabled/*。先说后者,在 /etc/nginx/ 目录下除了 sites-enabled 目录还有个 sites-available 目录,而真正的配置文件放置于 sites-available 目录内,当需要启用虚拟主机时创建链接到 sites-enabled,如:

$ sudo ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/

反之,当删除 sites-enabled 目录内当某个虚拟主机链接文件,就是将该虚拟主机禁用,这样的好处是可以在禁用某个虚拟主机的同时又将其配置文件进行保留,在下次使用时不用再写一次配置文件。按《NGINX Cookbook》这样的做法惯例已经废弃了。

所以现在更推荐的是使用前者 /etc/nginx/conf.d/*.conf,可以看到它匹配的是以 .conf 结尾的文件,所以想要达到上述同样效果也很简单,如果想禁用某个虚拟主机的配置,那么将其后缀名进行修改,如 example.com.conf.bak 就不会启用了。

回到编译配置,编译安装的默认配置没有给出明确的包含其他配置 include 语句

...
http {
    include       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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    include /usr/local/etc/nginx/*.conf;
...

此处我将包含其他配置设为 /usr/local/etc/nginx/*.conf(你可能需要在 /usr/local/etc/ 下新建名为 nginx 的目录。

$ sudo mkdir /usr/local/etc/nginx

小结

  1. 通过预先构建和源码构建安装的 NGINX,一般来说配置文件的默认路径有所不同;
  2. 不要直接将新建站点的配置信息直接写入到 NGINX 的主配置文件 nginx.conf 中,这样并不利于管理和维护;
  3. 接上一条,参照前文所述将不同站点配置写成各自独立的 .conf 文件存入如 /etc/nginx/conf.d/ 这样的目录中,在主配置文件 nginx.conf,利用 include 语句组织调用它们;
  4. Debian 系预先构建的 NGINX 默认是将站点独立配置文件写入到 sites-enabled 目录下然后链接到 sites-available,这个方法已被废弃,能用但不建议这么用;