Nginx安装配置详解、Nginx配置https反向代理示例

Nginx 安装

软硬件环境:CentOS 7.6_64位

安装依赖环境

yum -y install make zlib zlib-devel gcc-c++ libtool openssl openssl-devel pcre pcre-devel

查看pcre版本

[root@yaenli pcre]# pcre-config --version

安装Nginx

  1. 下载Nginx安装包:手动从官网地址 nginx: download,下载安装包上传至服务器目录或者采用如下命令

    [root@yaenli src]# cd /usr/local/src/
    [root@yaenli src]# wget http://nginx.org/download/nginx-1.22.0.tar.gz
    
  2. 解压安装包

    [root@yaenli src]# tar zxvf nginx-1.22.0.tar.gz
    
  3. 进入安装目录执行配置命令创建makefile文件

    [root@yaenli src]# cd nginx-1.22.0
    ./configure \
    --prefix=/usr/local/nginx \
    --with-http_stub_status_module \
    --with-http_ssl_module \
    --with-http_v2_module \
    --with-pcre
    
    

    注1:\ 代表在命令行中换行,用于提高可读性

    注2:configure参数官方说明:Building nginx from Sources

    部分模块说明:(后续可以根据需要依据此参数增减模块)

    http_ssl_module:用于支持https

    http_v2_module:用于支持HTTP/2

    配置结果:

    Configuration summary
      + using system PCRE library
      + using system OpenSSL library
      + using system zlib library
    
      nginx path prefix: "/usr/local/nginx"
      nginx binary file: "/usr/local/nginx/sbin/nginx"
      nginx modules path: "/usr/local/nginx/modules"
      nginx configuration prefix: "/usr/local/nginx/conf"
      nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
      nginx pid file: "/usr/local/nginx/logs/nginx.pid"
      nginx error log file: "/usr/local/nginx/logs/error.log"
      nginx http access log file: "/usr/local/nginx/logs/access.log"
      nginx http client request body temporary files: "client_body_temp"
      nginx http proxy temporary files: "proxy_temp"
      nginx http fastcgi temporary files: "fastcgi_temp"
      nginx http uwsgi temporary files: "uwsgi_temp"
      nginx http scgi temporary files: "scgi_temp"
    
    
  4. 编译安装

    [root@yaenli nginx-1.22.0]# make && make install
    
  5. 查看Nginx版本

    [root@yaenli nginx-1.22.0]# /usr/local/nginx/sbin/nginx -V
    

    至此,安装完成。

Nginx 配置

使用NGINXConfig完成配置工作。

NGINXConfig是一个在线的可视化的Nginx配置工具,地址:NGINXConfig | DigitalOcean

使用配置方法:

  1. 进入你的 NGINX服务器上的配置目录:

    cd /usr/local/nginx/conf
    
  2. 创建当前NGINX配置的备份:

    tar -czvf nginx_$(date +'%F_%H-%M-%S').tar.gz nginx.conf sites-available/ sites-enabled/ nginxconfig.io/
    
  3. 使用tar解压新的配置文件(从NGINXConfig上下载)

    tar -xzvf nginxconfig.io-example.com.tar.gz | xargs chmod 0644
    
  4. 服务器上运行此命令生成Diffie-Hellman keys:

    openssl dhparam -out /usr/local/nginx/conf/dhparam.pem 2048
    
  5. 重新加载NGINX以载入新的配置:

    sudo nginx -t && sudo systemctl reload nginx
    

https的反向代理配置示例

单应用的https反向代理,采用模块化配置方法Nginx配置示例

示例的具体配置文件内容如下:

  • /usr/local/nginx/conf/nginx.conf

# Generated by nginxconfig.io
# See nginxconfig.txt for the configuration share link

user                 root;
pid                  /run/nginx.pid;
worker_processes     auto;
worker_rlimit_nofile 65535;

# Load modules
include              /usr/local/nginx/conf/modules-enabled/*.conf;

events {
    multi_accept       on;
    worker_connections 65535;
}

http {
    charset                utf-8;
    sendfile               on;
    tcp_nopush             on;
    tcp_nodelay            on;
    server_tokens          off;
    log_not_found          off;
    types_hash_max_size    2048;
    types_hash_bucket_size 64;
    client_max_body_size   16M;

    # MIME
    include                mime.types;
    default_type           application/octet-stream;

    # Logging
    access_log             logs/access.log;
    error_log              logs/error.log warn;

    # SSL
    ssl_session_timeout    1d;
    ssl_session_cache      shared:SSL:10m;
    ssl_session_tickets    off;

    # Diffie-Hellman parameter for DHE ciphersuites
    ssl_dhparam            /usr/local/nginx/conf/dhparam.pem;

    # Mozilla Intermediate configuration
    ssl_protocols          TLSv1.2 TLSv1.3;
    ssl_ciphers            ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;

    # OCSP Stapling
    ssl_stapling           on;
    ssl_stapling_verify    on;
    resolver               1.1.1.1 1.0.0.1 8.8.8.8 8.8.4.4 208.67.222.222 208.67.220.220 valid=60s;
    resolver_timeout       2s;

    # Connection header for WebSocket reverse proxy
    map $http_upgrade $connection_upgrade {
        default upgrade;
        ""      close;
    }

    map $remote_addr $proxy_forwarded_elem {

        # IPv4 addresses can be sent as-is
        ~^[0-9.]+$        "for=$remote_addr";

        # IPv6 addresses need to be bracketed and quoted
        ~^[0-9A-Fa-f:.]+$ "for=\"[$remote_addr]\"";

        # Unix domain socket names cannot be represented in RFC 7239 syntax
        default           "for=unknown";
    }

    map $http_forwarded $proxy_add_forwarded {

        # If the incoming Forwarded header is syntactically valid, append to it
        "~^(,[ \\t]*)*([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\"([\\t \\x21\\x23-\\x5B\\x5D-\\x7E\\x80-\\xFF]|\\\\[\\t \\x21-\\x7E\\x80-\\xFF])*\"))?(;([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\"([\\t \\x21\\x23-\\x5B\\x5D-\\x7E\\x80-\\xFF]|\\\\[\\t \\x21-\\x7E\\x80-\\xFF])*\"))?)*([ \\t]*,([ \\t]*([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\"([\\t \\x21\\x23-\\x5B\\x5D-\\x7E\\x80-\\xFF]|\\\\[\\t \\x21-\\x7E\\x80-\\xFF])*\"))?(;([!#$%&'*+.^_`|~0-9A-Za-z-]+=([!#$%&'*+.^_`|~0-9A-Za-z-]+|\"([\\t \\x21\\x23-\\x5B\\x5D-\\x7E\\x80-\\xFF]|\\\\[\\t \\x21-\\x7E\\x80-\\xFF])*\"))?)*)?)*$" "$http_forwarded, $proxy_forwarded_elem";

        # Otherwise, replace it
        default "$proxy_forwarded_elem";
    }

    # Load configs
    include /usr/local/nginx/conf/conf.d/*.conf;
    include /usr/local/nginx/conf/sites-enabled/*;
}
  • /usr/local/nginx/conf/sites-enabled/example.com.conf

server {
    listen              443 ssl;
    listen              [::]:443 ssl;
    server_name         example.com;

    # SSL
    ssl_certificate     /usr/local/nginx/conf/ssl/example.com.crt;
    ssl_certificate_key /usr/local/nginx/conf/ssl/example.com.key;

    # security
    include             nginxconfig.io/security.conf;

    # logging
    access_log          logs/example.com.access.log;
    error_log           logs/example.com.error.log warn;

    # reverse proxy
    location / {
        proxy_pass            http://127.0.0.1:3000;
        proxy_set_header Host $host;
        include               nginxconfig.io/proxy.conf;
    }

    # additional config
    include nginxconfig.io/general.conf;
}

# HTTP redirect
server {
    listen      80;
    listen      [::]:80;
    server_name example.com;
    return      301 https://example.com$request_uri;
}
  • /usr/local/nginx/conf/nginxconfig.io/security.conf

# security headers
add_header X-XSS-Protection        "1; mode=block" always;
add_header X-Content-Type-Options  "nosniff" always;
add_header Referrer-Policy         "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: ws: wss: data: blob: 'unsafe-inline'; frame-ancestors 'self';" always;
add_header Permissions-Policy      "interest-cohort=()" always;

# . files
location ~ /\.(?!well-known) {
    deny all;
}
  • /usr/local/nginx/conf/nginxconfig.io/general.conf

# favicon.ico
location = /favicon.ico {
    log_not_found off;
    access_log    off;
}

# robots.txt
location = /robots.txt {
    log_not_found off;
    access_log    off;
}

# gzip
gzip            on;
gzip_vary       on;
gzip_proxied    any;
gzip_comp_level 6;
gzip_types      text/plain text/css text/xml application/json application/javascript application/rss+xml application/atom+xml image/svg+xml;
  • /usr/local/nginx/conf/nginxconfig.io/proxy.conf

proxy_http_version                 1.1;
proxy_cache_bypass                 $http_upgrade;

# Proxy SSL
proxy_ssl_server_name              on;

# Proxy headers
proxy_set_header Upgrade           $http_upgrade;
proxy_set_header Connection        $connection_upgrade;
proxy_set_header X-Real-IP         $remote_addr;
proxy_set_header Forwarded         $proxy_add_forwarded;
proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host  $host;
proxy_set_header X-Forwarded-Port  $server_port;

# Proxy timeouts
proxy_connect_timeout              60s;
proxy_send_timeout                 60s;
proxy_read_timeout                 60s;
  • /usr/local/nginx/conf/nginxconfig.txt

https://www.digitalocean.com/community/tools/nginx?domains.0.server.documentRoot=%2Fnccloud&domains.0.server.redirectSubdomains=false&domains.0.https.http2=false&domains.0.https.hsts=false&domains.0.https.certType=custom&domains.0.php.php=false&domains.0.reverseProxy.reverseProxy=true&domains.0.routing.root=false&domains.0.routing.index=index.html&domains.0.routing.fallbackHtml=true&domains.0.logging.accessLog=true&domains.0.logging.errorLog=true&global.logging.accessLog=logs%2Faccess.log&global.logging.errorLog=logs%2Ferror.log%20warn&global.nginx.nginxConfigDirectory=%2Fusr%2Flocal%2Fnginx%2Fconf%2F&global.nginx.user=root&global.tools.symlinkVhost=false&global.app.lang=zhCN

检查配置文件正确性

[root@yaenli conf]# /usr/local/nginx/sbin/nginx -t

Nginx 启停

/usr/local/nginx/sbin/nginx	  		 # 启动 Nginx
/usr/local/nginx/sbin/nginx -s reload            # 重新载入配置文件
/usr/local/nginx/sbin/nginx -s reopen            # 重启 Nginx
/usr/local/nginx/sbin/nginx -s stop              # 停止 Nginx