Ubuntu安装Nginx


1、安装依赖

sudo apt-get update

#安装依赖:gcc、g++依赖库
sudo apt-get install build-essential libtool

#安装 pcre依赖库(http://www.pcre.org/)
sudo apt-get install libpcre3 libpcre3-dev

#安装 zlib依赖库(http://www.zlib.net)
sudo apt-get install zlib1g-dev

#安装ssl依赖库
sudo apt-get install openssl libssl-dev

(1)PCRE库支持正则表达式。如果我们在配置文件nginx.conf中使用了正则表达式,那么在编译Nginx时就必须把PCRE库编译进Nginx,因为Nginx的HTTP模块需要靠它来解析正则表达式。另外,pcre-devel是使用PCRE做二次开发时所需要的开发库,包括头文件等,这也是编译Nginx所必须使用的

(2)zlib库用于对HTTP包的内容做gzip格式的压缩,如果我们在nginx.conf中配置了gzip on,并指定对于某些类型(content-type)的HTTP响应使用gzip来进行压缩以减少网络传输量,则在编译时就必须把zlib编译进Nginx

(3)如果服务器不只是要支持HTTP,还需要在更安全的SSL协议上传输HTTP,那么需要拥有OpenSSL。另外,如果我们想使用MD5、SHA1等散列函数,那么也需要安装它

2、下载解压  http://nginx.org/en/download.html

#下载
sudo wget http://nginx.org/download/nginx-1.20.2.tar.gz
#解压
sudo tar -zxvf nginx-1.20.2.tar.gz 

cd nginx-1.20.2

(1)mianline版本,版本号中间数字一般为奇数,更新快,一个月就会发布一个新版本,最新功能,bug修复等,稳定性差点。

(2)stable版本:稳定版,版本号中间数字一般为偶数。经过了长时间的测试,比较稳定,商业化环境中使用这种版本。

(3)Lengacy版本,遗产,遗留版本,以往的老版本。

3、编译Nginx信息

 sudo vim src/core/nginx.h

#修改前
#define nginx_version      1020002
#define NGINX_VERSION      "1.20.2"
#define NGINX_VER          "nginx/" NGINX_VERSION

#修改后
#define nginx_version      1020002
#define NGINX_VERSION      "1.20.2"
#define NGINX_VER          "Web Server/" NGINX_VERSION


#版本号也可以去掉,为了方便查看,我选择了保留
sudo vim src/http/ngx_http_header_filter_module.c

#修改前
static u_char ngx_http_server_string[] = "Server: nginx" CRLF;
static u_char ngx_http_server_full_string[] = "Server: " NGINX_VER CRLF;
static u_char ngx_http_server_build_string[] = "Server: " NGINX_VER_BUILD CRLF;

#修改后
static u_char ngx_http_server_string[] = "Server: Web Server" CRLF;
static u_char ngx_http_server_full_string[] = "Server: Web Server" CRLF;
static u_char ngx_http_server_build_string[] = "Server: Web Server" CRLF;
sudo vim src/http/ngx_http_special_response.c
#注意修改后无引号,因为修改前NGINX_VER为变量

#修改前
static u_char ngx_http_error_full_tail[] =
"
" NGINX_VER "
" CRLF "" CRLF "" CRLF ; static u_char ngx_http_error_build_tail[] = "
" NGINX_VER_BUILD "
" CRLF "" CRLF "" CRLF ; static u_char ngx_http_error_tail[] = "
nginx
" CRLF "" CRLF "" CRLF ; #修改后 static u_char ngx_http_error_full_tail[] = "
Web Server
" CRLF "" CRLF "" CRLF ; static u_char ngx_http_error_build_tail[] = "
Web Server
" CRLF "" CRLF "" CRLF ; static u_char ngx_http_error_tail[] = "
Web Server
" CRLF "" CRLF "" CRLF ;

4、编译安装

#如果你从包管理器安装NGINX,你可以在这个位置/etc/nginx/sites-enabled/default找到你的NGINX配置
#如果你从源代码安装或构建NGINX,你可以在这个位置/etc/nginx/nginx.conf找到你的NGINX配置(注意:默认在/usr/local/nginx下)

sudo ./configure --prefix=/var/www/html --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --http-log-path=/home/d/log/nginx/access.log --error-log-path=/home/d/log/nginx/error.log --with-pcre --lock-path=/var/lock/nginx.lock --pid-path=/var/run/nginx.pid --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module --with-http_gzip_static_module

–prefix 指定安装路径
–with-http_stub_status_module 允许查看nginx状态的模块
–with-http_ssl_module 支持https的模块
-with-http_v2_module 支持 HTTP/2
-with-http_gzip_static_module 支持压缩

sudo make 
sudo make install

参数说明:https://www.nginx.com/resources/wiki/start/topics/tutorials/installoptions/

查看安装版本

ubuntu@VM-0-9-ubuntu:~/nginx-1.20.2$ nginx -V
nginx version: Web Server/1.20.2
built by gcc 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)
built with OpenSSL 1.1.1f  31 Mar 2020
TLS SNI support enabled
configure arguments: --prefix=/var/www/html --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --http-log-path=/home/d/log/nginx/access.log --error-log-path=/home/d/log/nginx/error.log --with-pcre --lock-path=/var/lock/nginx.lock --pid-path=/var/run/nginx.pid --with-http_stub_status_module --with-http_ssl_module --with-http_v2_module --with-http_gzip_static_module

5、启动和监视Nginx

#systemd 可用于创建服务文件以启动和监视
#生成service文件
sudo vim /etc/systemd/system/nginx.service

#在打开的文件中写入以下内容
[Unit]
Description=Nginx running on Ubuntu
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/usr/sbin/nginx -s reload
ExecStop=/usr/sbin/nginx -s quit
PrivateTmp=true

[Install]
WantedBy=multi-user.target

#重新加载服务文件
sudo systemctl daemon-reload 
#生效
sudo systemctl enable nginx.service
#启动
sudo systemctl start nginx.service
#停止
sudo systemctl stop nginx.service
#重启
sudo systemctl restart nginx.service
#运行状态
sudo systemctl status nginx.service
#查找Nginx安装路径
whereis nginx

#查看Nginx进程
ps -ef|grep nginx

#启动Nginx
sudo nginx

#停止Nginx
sudo nginx -s stop 
sudo nginx -s quit

#重新加载Nginx配置
sudo nginx  -s reload

#查看配置文件语法
 sudo nginx  -t

6、关闭Nginx相关信息

#关闭Nginx版本信息
sudo vim /etc/nginx/nginx.conf
#在打开的文件中找到http节点,加入以下设置
server_tokens off;

#删除Nginx默认页信息
#打开文件并删除页面里的相关信息
sudo vim /var/www/html/html/index.html

#不允许Ip访问,要开文件准备一个新的server节点
sudo vim /etc/nginx/nginx.conf
server {
    listen       80 default;
    return      404;
}

#重新加载配置
sudo nginx -s reload
sudo apt-get remove nginx nginx-common 
# 卸载删除除了配置文件以外的所有文件。

sudo apt-get purge nginx nginx-common 
# 卸载所有东东,包括删除配置文件。

sudo apt-get autoremove 
# 在上面命令结束后执行,主要是卸载删除Nginx的不再被使用的依赖包。

sudo apt-get remove nginx-full nginx-common 
#卸载删除两个主要的包。  sudo service nginx restart  #重启nginx

7、设置Nginx用户

#打开配置文件
sudo vim /etc/nginx/nginx.conf

#打开
#user  nobody;
#修改后
user  www-data;

8、调优

#设置进程数量
sudo vim /etc/nginx/nginx.conf

worker_processes  auto;#也可设置具体的cpu核数
worker_cpu_affinity auto;

#设置Nginx用户最大打开文件数
worker_rlimit_nofile 65535;
#设置Nginx用户最大打开文件数
sudo vim /etc/security/limits.conf
www-data  -  nofile  65535

#超时设置
#给客户端分配keep-alive链接超时时间。服务器将在这个超时时间过后关闭链接
keepalive_timeout  60;
#client_header_timeout和client_body_timeout设置请求头和请求体(各自)的超时时间,如果没有发送请求头和请求体,Nginx服务器会返回408错误或者request time out
client_body_timeout 10;
client_header_timeout 10;
#指定客户端的响应超时时间。这个设置不会用于整个转发器,而是在两次客户端读取操作之间。如果在这段时间内,客户端没有读取任何数据,Nginx就会关闭连接
send_timeout 10;


#事件处理模型
events {
  #使用epoll的I/O 模型。linux建议epoll,FreeBSD建议采用kqueue,window下不指定。
  use epoll;
  worker_connections 65535;
}

#开启高效传输模式
http {
  sendfile on; # 开启高效文件传输模式。
  tcp_nopush on; #需要在sendfile开启模式才有效,防止网路阻塞,积极的减少网络报文段的数量。将响应头和正文的开始部分一起发送,而不一个接一个的发送。
}


#代理设置
sudo vim /etc/nginx/proxy.conf 
proxy_redirect          off;
proxy_set_header        Host $host;
proxy_set_header        X-Real-IP $remote_addr;
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header        X-Forwarded-Proto $scheme;
client_max_body_size    10m;
client_body_buffer_size 128k;
proxy_connect_timeout   90;
proxy_send_timeout      90;
proxy_read_timeout      90;
proxy_buffers           32 4k;
#然后引入配置
sudo vim /etc/security/limits.conf
http {
    include        /etc/nginx/proxy.conf;
}

#保护Nginx免受点击劫持的侵害
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
#X-Frame-Options: 响应头表示是否允许浏览器加载frame等属性,有三个配置DENY禁止任何网页被嵌入,SAMEORIGIN只允许本网站的嵌套,ALLOW-FROM允许指定地址的嵌套
#X-XSS-Protection: 表示启用XSS过滤(禁用过滤为X-XSS-Protection: 0),mode=block表示若检查到XSS攻击则停止渲染页面
#X-Content-Type-Options: 响应头用来指定浏览器对未指定或错误指定Content-Type资源真正类型的猜测行为,nosniff 表示不允许任何猜测


#开启GZIP
gzip on;       #表示开启压缩功能
#表示允许压缩的页面最小字节数 默认值: 0 ,不管页面多大都压缩,建议设置成大于1K。如果小于1K可能会越压越大
gzip_min_length  1k; 
#压缩缓存区大小 默认值: gzip_buffers 4 4k/8k 
gzip_buffers     4 16k; 
#压缩版本 默认值: gzip_http_version 1.1(就是说对HTTP/1.1协议的请求才会进行gzip压缩)
gzip_http_version 1.1; 
#压缩比率,默认值:1(建议选择为4)压缩级别 1-9,级别越高压缩率越大,当然压缩时间也就越长
gzip_comp_level 4; 
#默认值: gzip_types text/html (默认不对js/css文件进行压缩)
gzip_types text/plain text/css text/xml application/xml application/xml+rss application/json;
# 和http头有关系,加个vary头,给代理服务器用的,有的浏览器支持压缩,有的不支持,所以避免浪费不支持的也压缩,所以根据客户端的HTTP头来判断,是否需要压缩
gzip_vary on;


#HTTPS服务器优化
#SSL 操作会消耗额外的 CPU 资源,最占用 CPU 的操作是 SSL 握手,有两种方法可以最小化每个客户端的这些操作的数量:第一种是启用 keepalive 连接以通过一个连接发送多个请求,第二种是重用 SSL 会话参数以避免并行和后续连接的 SSL 握手,会话存储在工作人员之间共享的 SSL 会话缓存中,并由 ssl_session_cache 指令配置。1 兆字节的缓存包含大约 4000 个会话。默认缓存超时为 5 分钟。它可以通过使用增加 ssl_session_timeout 指令。以下是针对具有 10 兆字节共享会话缓存的多核系统优化的示例配置
worker_processes auto;

http {
    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;

    server {
        listen              443 ssl;
        server_name         www.example.com;
        keepalive_timeout   70;
        ...        
#详情:http://nginx.org/en/docs/http/configuring_https_servers.html#name_based_https_servers


#限流
#limit_req_zone 用来限制单位时间内的请求数,即速率限制,采用的漏桶算法 "leaky bucket"。
#limit_req_conn 用来限制同一时间连接数,即并发限制。

http {
    #单个IP只允许1秒内发起5次请求
    limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s 
    server {
        location /search/ {
            #允许在突破情况下,还可以多处理5个请求,超出直接拒绝
            limit_req zone=one burst=5 nodelay;
            #自定义 status 返回值的状态 默认404
            limit_req_status 598;
        }
} 
#详情:https://www.cnblogs.com/biglittleant/p/8979915.html

#查看cpu核心数
cat /proc/cpuinfo|grep "cpu cores"|uniq

#查看cpu使用率
top  回车后按 1

#查看nginx进程绑定在哪个CPU上
ps -eo pid,args,psr | grep [n]ginx

 完整nginx配置

user  www-data;

worker_processes  auto;
worker_cpu_affinity auto;
worker_rlimit_nofile 65535;

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

#pid        logs/nginx.pid;


events {
    use epoll;
    worker_connections 65535;
}


http {
    include        /etc/nginx/proxy.conf;
    include       mime.types;
    default_type  application/octet-stream;

    limit_req_zone $binary_remote_addr zone=one:10m rate=5r/s;

    #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;
    server_tokens off;

    sendfile        on;
    tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  60;
    client_body_timeout 10;
    client_header_timeout 10;
    send_timeout 10;

    ssl_session_cache   shared:SSL:10m;
    ssl_session_timeout 10m;

    #gzip  on;
    gzip on;
    gzip_vary on;
    gzip_min_length  1k;
    gzip_buffers     4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 4;
    gzip_types text/plain text/css text/xml application/xml application/xml+rss application/json;

    server {
            listen 80;
            listen 443 ssl http2;
            listen [::]:443 ssl http2;
            server_name  localhost;
            ssl_certificate localhost.crt; 
            ssl_certificate_key localhost.key; 
            
            add_header X-Frame-Options "SAMEORIGIN";
            add_header X-XSS-Protection "1; mode=block";
            add_header X-Content-Type-Options "nosniff";
            location / {
                    limit_req zone=one burst=5 nodelay;
                    proxy_pass         http://localhost:5001;
                    proxy_http_version 1.1;
                    proxy_set_header   Upgrade $http_upgrade;
                    proxy_set_header   Connection keep-alive;
                    proxy_set_header   Host $host;
                    proxy_cache_bypass $http_upgrade;
                    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
                    proxy_set_header   X-Forwarded-Proto $scheme;
            }
    }

    server {
            listen   80 default_server;
            return   404;
    }

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

参考文献:https://blog.csdn.net/A156348933/article/details/85335089

                  https://blog.csdn.net/lingbing5719/article/details/116479391

                  https://www.jianshu.com/p/e49389635d6d