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

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

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