# Nginx

# 安装过程

在 ubuntu 发行版下只需一条命令即可安装 nginx

sudo apt-get install nginx
如果发现安装的版本不是最新版本,则需要一些前置操作
sudo apt install curl gnupg2 ca-certificates lsb-release

配置稳定版 nginx 仓库

echo "deb http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" \
    | sudo tee /etc/apt/sources.list.d/nginx.list

下一步,导入官方 nginx 签名

curl -fsSL https://nginx.org/keys/nginx_signing.key | sudo apt-key add -

验证签名

sudo apt-key fingerprint ABF5BD827BD9BF62

最后的输出

pub   rsa2048 2011-08-19 [SC] [expires: 2024-06-14]
      573B FD6B 3D8F BC64 1079  A6AB ABF5 BD82 7BD9 BF62
uid   [ unknown] nginx signing key <signing-key@nginx.com>

最后重新安装 nginx

sudo apt update
sudo apt install nginx

需要说明的是这样安装网速超级慢

可以使用 nginx -v 查看安装的版本】
本文安装的版本文 1.18

# 配置说明

nginx 配置文件的关系:

配置代理目录 /etc/nginx/sites-available/ 存放具体 Server 的配置文件

启动配置代理目录 /etc/nginx/sites-enabled/ 存放的链接文件,每个链接指向 sites-available 目录中的配置文件
具体命令为

sudo ln -s /etc/nginx/sites-available/availableFileName linkFileName
nginx.conf配置文件详解
##
# 全局配置
##
user www-data;             ## 配置 worker 进程的用户和组
worker_processes auto;     ## 配置 worker 进程启动的数量,建议配置为 CPU 核心数
error_log logs/error.log;  ## 全局错误日志
pid /run/nginx.pid;        ## 设置记录主进程 ID 的文件
worker_rlimit_nofile 8192; ## 配置一个工作进程能够接受并发连接的最大数
##
# 工作模式及连接数上限
##
events {
    # epoll 是多路复用 IO(I/O Multiplexing)中的一种方式,
    # 仅用于 Linux 2.6 以上内核,可以大大提高 Nginx 性能
    use epoll
        
    # 单个后台 worker process 进程的最大并发链接数
    # 并发总数 max_clients = worker_professes * worker_connections
    worker_connections 4096;  ## Defaule: 1024
    # multi_accept on;  ## 指明 worker 进程立刻接受新的连接
}
##
# http 模块
##
http {
    ##
    # Basic Settings
    ##
    
    #sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,
    #对于普通应用,必须设为 on,
    #如果用来进行下载等应用磁盘 IO 重负载应用,可设置为 off,
    #以平衡磁盘与网络 I/O 处理速度,降低系统的 uptime.
    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;  # this seems to be required for some vhosts
    # server_name_in_redirect off;
    
    include /etc/nginx/mime.types;  ## 设定 mine 类型
    default_type application/octet-stream;
   
    # 设定请求缓冲
    client_header_buffer_size    128k; # 指定客户端请求头缓存大小,当请求头大于 1KB 时会用到该项
    large_client_header_buffers  4 128k; # 最大数量和最大客户端请求头的大小
    
    ##
    # SSL Settings
    ##
    
    # 启用所有协议,禁用已废弃的不安全的 SSL 2 和 SSL 3
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # 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_disable "msie6";
    # 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/*; # 开启的 Server 服务配置
}
##
# 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;
    }
}

# 配置 HTTP 服务

# Virtual Host configuration for arlingbc.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
# 丢弃缺乏 Host 头的请求
server {
       listen 80;
       return 444;
}
server {
       listen 80;
       listen [::]:80;
       server_name example.com www.example.com;
       # 定义服务器的默认网站根目录位置
       root /var/www/example/;
       
       # Add index.php to the list if you are using PHP
       index index.html index.htm index.nginx-debian.html;
       # access log file 访问日志
       access_log logs/nginx.access.log main;
       
       # 禁止访问隐藏文件
       # Deny all attempts to access hidden files such as .htaccess, .htpasswd, .DS_Store (Mac).
       location ~ /\. {
                deny all;
                access_log off;
                log_not_found off;
       }
    
       # 默认请求
       location / {
                # 首先尝试将请求作为文件提供,然后作为目录,然后回退到显示 404。
                # try_files 指令将会按照给定它的参数列出顺序进行尝试,第一个被匹配的将会被使用。
                # try_files $uri $uri/ =404;
      
                try_files $uri $uri/ /index.php?path_info=$uri&$args =404;
                access_log off;
                expires max;
       }
    
       # 静态文件,nginx 自己处理
       location ~ ^/(images|javascript|js|css|flash|media|static)/ {
            
           #过期 30 天,静态文件不怎么更新,过期可以设大一点,
           #如果频繁更新,则可以设置得小一点。
           expires 30d;
       }
    
       # .php 请求
       location ~ \.php$ {
                try_files $uri =404;
                include /etc/nginx/fastcgi_params;
                fastcgi_pass unix:/var/run/php5-fpm.sock;
                fastcgi_index index.php;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_intercept_errors on;
       }
    
      # PHP 脚本请求全部转发到 FastCGI 处理。使用 FastCGI 默认配置.
      # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
      #
      #location ~ \.php$ {
      #       include snippets/fastcgi-php.conf;
      #
      #       # With php7.0-cgi alone:
      #       fastcgi_pass 127.0.0.1:9000;
      #       # With php7.0-fpm:
      #       fastcgi_pass unix:/run/php/php7.0-fpm.sock;
      #}
      
      # 拒绝访问. htaccess 文件,如果 Apache 的文档根与 nginx 的一致
      # deny access to .htaccess files, if Apache's document root
      # concurs with nginx's one
      #
      #location ~ /\.ht {
      #       deny all;
      #}
}

# 配置 HTTPS 服务

##
# 80 port
##
# 默认服务器,丢弃缺乏 Host 头的请求
server {
       listen 80;
       return 444;
}
server {
        listen 80;
        listen [::]:80;
        sever_name example.com www.example.com;
        rewrite ^(.*)$ https://$host$1 permanent;  ## 端口转发,301 重定向
}
##
# 443 port
##
server {
    
    ##
    # 阿里云参考配置
    ##
    
    listen 443;
    listen [::]:443;
    server_name example.com www.example.com;
    
    root /var/www/example/;    # 为虚拟服务器指明文档的根目录
    index index.html index.htm; # 给定 URL 文件
    
    ##
    # 部署 HTTP 严格传输安全(HSTS)
    ##
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload;"
    
    # Note: You should disable gzip for SSL traffic.
    # See: https://bugs.debian.org/773332
    gzip off;
    
    ##
    # SSL configuration
    ##
    
    ssl on;
    ssl_certificate   cert/certfile.pem;    # 证书
    ssl_certificate_key  cert/certfile.key; # 私钥
    ssl_session_timeout 5m; # 设置超时时间
    # 密码套件配置
    # 密码套件名称构成:密钥交换 - 身份验证 - 加密算法(算法 - 强度 - 模式)-MAC 或 PRF
    ssl_ciphers ECDHE-RSA-AES128-GCM- SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; 
    ssl_protocols TLSv1.2; # 设置 SSL/TSL 协议版本号
    ssl_prefer_server_ciphers on; # 控制密码套件优先级,让服务器选择要使用的算法套件
    ssl_buffer_size 1400; # 减少 TLS 缓冲区大小,可以显著减少首字节时间(《HTTPS 权威指南》P416)
    
    ##
    # location configuration
    ##
    
    # ...
}

# V1.18 版本配置

/etc/nginx/conf.d 目录下,复制 default.conf 然后配置一个端口 (开启 https), 例如把博客配置如下

server {
    listen       82 ssl;
    server_name  域名;
    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;
    ssl_certificate   /www/域名.pem;
    ssl_certificate_key  /www/域名.key;
    ssl_session_timeout 5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
    ssl_prefer_server_ciphers on;
    location / {
        root   /www/blog;
        index  index.html index.htm;
    }

推荐 HTTPS 自动化配置工具 Mozilla SSL Configuration Generator

# ngx_http_limit_req_module 模块

http {
    # 最大连接数
    # 分配一个共享内存区域,大小为 10M,限制下载连接数为 1
    limit_conn_zone $binary_remote_addr zone=connections:10m;
    # 最大并发数,每秒请求数(r/s),每分钟请求数(r/m)
    # 分配一个设置最大并发数的内存区域,大小 10M,limit_req 限制之前的请求速率 1 次 /s。
    # 使用 $binary_remote_addr 变量, 可以将每条状态记录的大小减少到 64 个字节,这样 1M 的内存可以保存大约 1 万 6 千个 64 字节的记录。
    limit_req_zone $binary_remote_addr zone=requests:10m rate=1r/s;
    # 设置日志记录级别
    # 当服务器因为频率过高拒绝或者延迟处理请求时可以记下相应级别的日志。
    limit_req_log_level warn;
    # immediately release socket buffer memory on timeout
    reset_timedout_connection on;
    server {
    
        # 仅对 search URL 有效
        location /search {
            
            # 限制速率
            # 最大延迟请求数量 10 个,超过则返回状态码 503
            limit_req zone=requests burst=3 nodelay;
        }
        
        # 限制客户端带宽,
        # 策略:允许小文件自由下载,但对于大文件则启用这种限制
        location /downloads {
            # 首先限制客户端的下载连接数为 1 
            limit_conn connections 1;
            # 下载完 1M 内容之后,启用 limit_rate 限制。
            limit_rate_after 1m;
            
            # 限制客户端下载下载内容的速率为 500k/s
            limit_rate 500k;
        }
    }
}

# 遗留问题

如何只开一个端口 ssl,例如 82 端口,此时用 http://localhost:82 访问会报 400 错误,如何解决 http 跳转 https 协议是个问题。

更新于 阅读次数

请我喝[茶]~( ̄▽ ̄)~*

Rick Lee 微信支付

微信支付

Rick Lee 支付宝

支付宝