Ubuntu Nginx编译安装及部署配置

1、安装依赖

sudo apt update && sudo apt upgrade -y

sudo apt install build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev libgd-dev libxml2 libxml2-dev uuid-dev -y

(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.22.1.tar.gz
#解压
sudo tar -zxvf nginx-1.22.1.tar.gz 

cd nginx-1.22.1

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

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

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

3、编译Nginx信息

 sudo vim src/core/nginx.h

#修改前
#define nginx_version      1022001
#define NGINX_VERSION      "1.22.1"
#define NGINX_VER          "nginx/" NGINX_VERSION

#define NGINX_VAR          "NGINX"

#修改后
#define nginx_version      1020002
#define NGINX_VERSION      ""
#define NGINX_VER          "None" NGINX_VERSION

#define NGINX_VAR          "None"


#版本号也可以去掉,为了方便查看,我选择了保留
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: None" CRLF;
static u_char ngx_http_server_full_string[] = "Server: None" CRLF;
static u_char ngx_http_server_build_string[] = "Server: None" CRLF;
sudo vim src/http/ngx_http_special_response.c
#注意修改后无引号,因为修改前NGINX_VER为变量,也可以直接删除整行

#修改前
static u_char ngx_http_error_full_tail[] =
"<hr><center>" NGINX_VER "</center>" CRLF
"</body>" CRLF
"</html>" CRLF
;


static u_char ngx_http_error_build_tail[] =
"<hr><center>" NGINX_VER_BUILD "</center>" CRLF
"</body>" CRLF
"</html>" CRLF
;


static u_char ngx_http_error_tail[] =
"<hr><center>nginx</center>" CRLF
"</body>" CRLF
"</html>" CRLF
;

#修改后

static u_char ngx_http_error_full_tail[] =
"</body>" CRLF
"</html>" CRLF
;


static u_char ngx_http_error_build_tail[] =
"</body>" CRLF
"</html>" CRLF
;


static u_char ngx_http_error_tail[] =
"</body>" CRLF
"</html>" CRLF
;


static u_char ngx_http_msie_padding[] =
""
;

4、编译安装

sudo mkdir -p /home/d/nginx/tmp

sudo ./configure --prefix=/var/www/html --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --http-log-path=/home/d/nginx/log/access.log --error-log-path=/home/d/nginx/log/error.log --http-fastcgi-temp-path=/home/d/nginx/tmp/fastcgi_tmp --http-proxy-temp-path=/home/d/nginx/tmp/proxy_tmp --http-client-body-temp-path=/home/d/nginx/tmp/client_body_temp --with-pcre --lock-path=/var/lock/nginx.lock --pid-path=/var/run/nginx.pid --modules-path=/etc/nginx/modules --with-http_ssl_module  --with-http_v2_module --user=www-data --group=www-data

sudo make && sudo make install

#删除下载的安装包
cd ..
sudo rm -r nginx-1.22.1 && sudo rm -r nginx-1.22.1.tar.gz

–prefix 指定安装路径
–with-http_ssl_module 支持https的模块
-with-http_v2_module 支持 HTTP/2

 

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

查看安装版本

ubuntu@VM-0-9-ubuntu:~/nginx-1.22.1$ nginx -V
nginx version: Unknown/1.22.1
built by gcc 9.4.0 (Ubuntu 9.4.0-1ubuntu1~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/nginx/log/access.log --error-log-path=/home/d/nginx/log/error.log --http-fastcgi-temp-path=/home/d/nginx/tmp/fastcgi_tmp --http-proxy-temp-path=/home/d/nginx/tmp/proxy_tmp --http-client-body-temp-path=/home/d/nginx/tmp/client_body_temp --with-pcre --lock-path=/var/lock/nginx.lock --pid-path=/var/run/nginx.pid --modules-path=/etc/nginx/modules --with-http_ssl_module --with-http_v2_module --user=www --group=www

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 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

 注意:server_tokens off时,nginx会把整个server头换为server:nginx,这将导致上边server信息的修改无效,解决办法,要么不改server,只关闭版本信息,要么server_tokens设置为on,上边的server头生效,二选一,暂未找到好的解决办法,有知道的麻烦留言告知一下,我怀疑当设置为off时,nginx会直接把server的值整体换为nginx,而不是去过滤nginx后边的版本信息。

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、Nginx优化配置

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

worker_processes  auto;#也可设置具体的cpu核数
#开启利用多核cpu的配置
worker_cpu_affinity auto;
#设置进程优先级取值范围-20到+20,-20级别最高。因此可以把这个值设置小一点,但不建议比内核进程的值低(通常为-5)
worker_priority -3;
#设置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 {
  accept_mutex on; #优化同一时刻只有一个请求而避免多个睡眠进程被唤醒的设置,on为防止被同时唤醒,默认为off,因此nginx刚安装完以后要进行适当的优化。
  multi_accept on; #只能在events模块设置,Nginx服务器的每个工作进程可以同时接受多个新的网络连接,但是需要在配置文件中配置,此指令默认为关闭,即默认为一个工作进程只能一次接受一个新的网络连接,打开后几个同时接受多个
  #使用epoll的I/O 模型。linux建议epoll,FreeBSD建议采用kqueue,window下不指定。
  use epoll;
  worker_connections 65535;
}

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


#保护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;

#代理设置
sudo vim /etc/nginx/proxy.conf 
proxy_redirect          off;
proxy_http_version      1.1;
proxy_cache_bypass      $http_upgrade;
proxy_set_header        Upgrade $http_upgrade;
proxy_set_header        Connection keep-alive;
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;
proxy_set_header        X-Forwarded-Host $server_name;
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;
#然后引入配置
http {
    include        /etc/nginx/proxy.conf;
}

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

http {
    ssl_session_cache   shared:SSL:15m;
    ssl_session_timeout 30m;
    ssl_prefer_server_ciphers off #如果ssl协议只支持tlsv1.2 tlsv1.3新协议,设置为 off
    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
#https://www.nginx.com/resources/wiki/start/topics/examples/SSL-Offloader/

#限流
#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_priority -3;
worker_rlimit_nofile 65535;

events {
    accept_mutex on;
    multi_accept on; 
    use epoll;
    worker_connections 65535;
}


http {
    map_hash_bucket_size 128;
    include       proxy.conf;
    include       mime.types;
    default_type  application/octet-stream;

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

    server_tokens off;

    tcp_nodelay off;
    sendfile on;
    tcp_nopush on;

    resolver_timeout 10;
    keepalive_timeout 60;
    client_body_timeout 10;
    client_header_timeout 10;
    send_timeout 10;


    gzip on;
    gzip_vary on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_http_version 1.1;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/x-component text/xml application/xml application/xhtml+xml application/json image/x-icon image/bmp image/svg+xml application/atom+xml text/javascript application/javascript application/x-javascript application/pdf application/postscript application/rtf application/msword application/vnd.ms-powerpoint application/vnd.ms-excel application/vnd.ms-fontobject application/vnd.wap.wml application/x-font-ttf application/x-font-opentype;

    server {
            listen 443 ssl http2;
            listen [::]:443 ssl http2;
            server_name www; 
            ssl_certificate www.crt; 
            ssl_certificate_key www.key; 
            include ssl.conf;
            location / {
                    limit_req zone=one burst=5 nodelay;
                    proxy_pass         http://localhost:5001;
            }
    }

    server {
            listen 80;
            server_name *.yhq.var.net.cn;
            return 301 https://$host;
    }

    server {
            listen 80 default_server;
            #server_name _;
            return 404;
    }

}
View Code
#proxy.conf

proxy_redirect          off;
proxy_http_version      1.1;
proxy_cache_bypass      $http_upgrade;
proxy_hide_header       Server;
proxy_hide_header       X-Powered-By;
proxy_hide_header       X-AspNet-Version;
proxy_hide_header       X-Application-Context;
proxy_set_header        Upgrade $http_upgrade;
proxy_set_header        Connection keep-alive;
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;
proxy_set_header        X-Forwarded-Host $server_name;
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;
View Code
ssl_session_cache shared:SSL:15m;
ssl_session_timeout 30m;
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;
ssl_session_tickets off;
ssl_prefer_server_ciphers off;
ssl_stapling on;
ssl_stapling_verify on;
    
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
View Code

 9、系统优化配置

#打开文件在最后追加以下内容
sudo vim /etc/sysctl.conf
#执行命令生效
sudo sysctl -p

# Avoid a smurf attack
net.ipv4.icmp_echo_ignore_broadcasts = 1

# Turn on protection for bad icmp error messages
net.ipv4.icmp_ignore_bogus_error_responses = 1

# Turn on syncookies for SYN flood attack protection
net.ipv4.tcp_syncookies = 1

# No source routed packets here
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0

# Turn on reverse path filtering
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

# Make sure no one can alter the routing tables
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.secure_redirects = 0

# Don't act as a router
net.ipv4.ip_forward = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

# Turn on execshild
kernel.exec-shield = 1
kernel.randomize_va_space = 1

# Tuen IPv6
net.ipv6.conf.default.router_solicitations = 0
net.ipv6.conf.default.accept_ra_rtr_pref = 0
net.ipv6.conf.default.accept_ra_pinfo = 0
net.ipv6.conf.default.accept_ra_defrtr = 0
net.ipv6.conf.default.autoconf = 0
net.ipv6.conf.default.dad_transmits = 0
net.ipv6.conf.default.max_addresses = 1

# Optimization for port usefor LBs
# Increase system file descriptor limit
fs.file-max = 65535

# Allow for more PIDs (to reduce rollover problems)
# !!! may break some programs 32768
#kernel.pid_max = 65536

# Increase system IP port limits
net.ipv4.ip_local_port_range = 2000 65000

# Increase TCP max buffer size setable using setsockopt()
net.ipv4.tcp_rmem = 4096 87380 8388608
net.ipv4.tcp_wmem = 4096 87380 8388608

# Increase Linux auto tuning TCP buffer limits
# min, default, and max number of bytes to use
# set max to at least 4MB, or higher if you use very high BDP paths
# Tcp Windows etc
net.core.rmem_max = 8388608
net.core.wmem_max = 8388608
net.core.netdev_max_backlog = 5000
net.ipv4.tcp_window_scaling = 1

 10、日志分隔

#按天进行日志分割并进行压缩打包保存,超过30天自动删除
sudo vim /home/d/nginx/log/nginx_cut_log.sh

#!/bin/bash
date=$(date +%F -d -1day)
cd /home/d/nginx/log
if [ ! -d bak ] ; then
        mkdir -p bak
fi
mv access.log bak/access_$date.log 
mv error.log bak/error_$date.log        
/usr/sbin/nginx -s reopen    

tar -jcvf bak/$date.tar.gz bak/access_$date.log bak/error_$date.log
find /home/d/nginx/log/bak -mtime +30 -name "*.gz" -exec rm -rf {} \;
find /home/d/nginx/log/bak -mtime +1 -name "*.log" -exec rm -rf {} \;


#授执行权限
sudo chmod 755 /home/d/nginx/log/nginx_cut_log.sh

#设置定时任务
#打开配置文件 
sudo crontab -e
#输入以下内容
0 1 * * * /bin/sh /home/d/nginx/log/nginx_cut_log.sh

#编辑创建一个定时服务
sudo crontab -e      
#查看当前用户的定时任务
sudo crontab -l       
#删除当前用户的定时任务
sudo crontab -r      

 

参考文献:https://www.armanism.com/blog/install-nginx-on-ubuntu

                  https://www.nginx.com/resources/wiki/start/

                  https://blog.csdn.net/A156348933/article/details/85335089

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

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

posted @ 2022-03-07 12:57  anech  阅读(1220)  评论(0编辑  收藏  举报