一、nginx下載安裝
版本nginx 1.15.5
系統環境centos7.5(本機ip192.168.199.228)
關閉selinux 和防火牆firewall
1、下載
wget http://nginx.org/download/nginx-1.15.5.tar.gz -P /usr/src
2、安裝
安裝大概過程
配置---編譯---安裝
配置 1)檢查環境 是否 滿足安裝條件 依賴解決 2)指定安裝方式 配置文件 命令文件 各種文件放哪里 開啟模塊功能【內 置模塊 三方模塊】 3)指定軟件安裝在那里
a、切換到usr/src目錄,解壓文件
[root@localhost src]# cd /usr/src [root@localhost src]# ls debug kernels nginx-1.15.5.tar.gz [root@localhost src]# tar xf nginx-1.15.5.tar.gz [root@localhost src]# ls debug kernels nginx-1.15.5 nginx-1.15.5.tar.gz [root@localhost src]#
查看配置方法
[root@localhost src]# pwd /usr/src [root@localhost src]# cd nginx-1.15.5 [root@localhost nginx-1.15.5]# ls auto CHANGES.ru configure html man src CHANGES conf contrib LICENSE README [root@localhost nginx-1.15.5]# ./configure --help #查看配置參數幫助
b、安裝各種依賴環境
[root@localhost src]# cd nginx-1.15.5 [root@localhost nginx-1.15.5]# yum -y install gcc pcre-devel zlib zlib-devel Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: mirror.vpshosting.com.hk * extras: centos.01link.hk * updates: hk.mirrors.thegigabit.com Resolving Dependencies --> Running transaction check ---> Package gcc.x86_64 0:4.8.5-39.el7 will be installed ...
gcc 編譯工具
pcre-devel 在nginx中url 需要用到這個包
zlib zlib-devel 解壓縮工具
對於 gcc,因為安裝nginx需要先將官網下載的源碼進行編譯,編譯依賴gcc環境,如果沒有gcc環境的話,需要安裝gcc。
對於 pcre,prce(Perl Compatible Regular Expressions)是一個Perl庫,包括 perl 兼容的正則表達式庫。nginx的http模塊使用pcre來解析正則表達式,所以需要在linux上安裝pcre庫。
對於 zlib,zlib庫提供了很多種壓縮和解壓縮的方式,nginx使用zlib對http包的內容進行gzip,所以需要在linux上安裝zlib庫。
c、指定目錄進行編譯
[root@localhost nginx-1.15.5]# ./configure --prefix=/usr/local/nginx checking for OS + Linux 3.10.0-862.el7.x86_64 x86_64 checking for C compiler ... found + using GNU C compiler + gcc version: 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC) ...
d、編譯make
make就是將源碼進行編譯生成可執行程序的過程
[root@localhost nginx-1.15.5]# pwd /usr/src/nginx-1.15.5 [root@localhost nginx-1.15.5]# ls auto CHANGES.ru configure html Makefile objs src CHANGES conf contrib LICENSE man README [root@localhost nginx-1.15.5]# make make -f objs/Makefile make[1]: Entering directory `/usr/src/nginx-1.15.5' cc -c -pipe -O -W -Wall -Wpointer-arith -Wno-unused-parameter -Werror -g -I src/core -I src/event -I src/event/modules -I src/os/unix -I objs \ ...
沒有error的話進行
e、make install完成安裝
[root@localhost nginx-1.15.5]# make install make -f objs/Makefile install make[1]: Entering directory `/usr/src/nginx-1.15.5' test -d '/usr/local/nginx' || mkdir -p '/usr/local/nginx' test -d '/usr/local/nginx/sbin' \ ...
完成安裝
二、nginx的相關目錄
nginx path prefix: "/usr/local/nginx" #nginx的安裝目錄 nginx binary file: "/usr/local/nginx/sbin/nginx" #nginx的啟動文件 nginx modules path: "/usr/local/nginx/modules" # nginx的模塊目錄 nginx configuration prefix: "/usr/local/nginx/conf" #nginx的配置文件位置 nginx configuration file: "/usr/local/nginx/conf/nginx.conf" #nginx的配置文件全路徑 nginx pid file: "/usr/local/nginx/logs/nginx.pid" #nginx的進程號 nginx error log file: "/usr/local/nginx/logs/error.log" #nginx的錯誤日志目錄 nginx http access log file: "/usr/local/nginx/logs/access.log" #nginx的訪問日志目錄
三、nginx的啟動與關閉、檢查配置文件
查看端口是否占用
方法一
安裝netstat 用netstat進行查看
[root@localhost nginx]# yum -y install net-tools Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile ... [root@localhost nginx]# netstat -ntpl Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 881/sshd tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 1128/master tcp6 0 0 :::22 :::* LISTEN 881/sshd tcp6 0 0 ::1:25 :::* LISTEN 1128/master
方法二
安裝lsof 用lsof 查看
[root@localhost nginx]# yum -y install lsof Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile ... [root@localhost nginx]# lsof -i :80 [root@localhost nginx]# #沒有顯示結果表示端口沒有被占用
啟動nginx方式
[root@localhost nginx]# lsof -i :80 [root@localhost nginx]# /usr/local/nginx/sbin/nginx #啟動nginx [root@localhost nginx]# lsof -i :80 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME nginx 11728 root 6u IPv4 38674 0t0 TCP *:http (LISTEN) nginx 11729 nobody 6u IPv4 38674 0t0 TCP *:http (LISTEN) [root@localhost nginx]# #nginx把80端口占用了
查看是否安裝成功
方法一:
用google瀏覽器地址欄輸入http://192.168.199.228(nginx安裝服務器的ip地址)
如果出現Welcome to nginx!頁面則安裝成功
方法二
用elinks 查看安裝是否成功,elinks不會有緩存,一般的google瀏覽器會有緩存
[root@localhost nginx]# yum -y install elinks Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: mirror.vpshosting.com.hk * extras: centos.01link.hk * updates: hk.mirrors.thegigabit.com ... [root@localhost nginx]# elinks http://192.168.199.228 --dump Welcome to nginx! If you see this page, the nginx web server is successfully installed and working. Further configuration is required. For online documentation and support please refer to [1]nginx.org. Commercial support is available at [2]nginx.com. Thank you for using nginx. References Visible links 1. http://nginx.org/ 2. http://nginx.com/ [root@localhost nginx]#
關閉 nginx
有3種方式:
方式1:快速停止
cd /usr/local/nginx/sbin ./nginx -s stop
此方式相當於先查出nginx進程id再使用kill命令強制殺掉進程。不太友好。
方式2:平緩停止
cd /usr/local/nginx/sbin ./nginx -s quit
此方式是指允許 nginx 服務將當前正在處理的網絡請求處理完成,但不在接收新的請求,之后關閉連接,停止工作。
方法3:killall
killall nginx
相當於直接殺死所有的關於nginx的進程
重啟 nginx
方式1:先停止再啟動
./nginx -s quit ./nginx
相當於先執行停止命令再執行啟動命令。
方式2:重新加載配置文件
./nginx -s reload
通常我們使用nginx修改最多的便是其配置文件 nginx.conf。修改之后想要讓配置文件生效而不用重啟 nginx,便可以使用此命令。
方法3:
killall -s HUP nginx
檢測配置文件語法是否正確
方式1:通過如下命令,指定需要檢查的配置文件
nginx -t -c /usr/local/nginx/conf/nginx.conf
方式2:通過如下命令,不加 -c 參數,默認檢測nginx.conf 配置文件。
nginx -t
四、Nginx配置文件詳解
nginx文件結構
... #全局塊 events { #events塊 ... } http #http塊 { ... #http全局塊 server #server塊 { ... #server全局塊 location [PATTERN] #location塊 { ... } location [PATTERN] { ... } } server { ... } ... #http全局塊 }
1、全局塊:配置影響nginx全局的指令。一般有運行nginx服務器的用戶組,nginx進程pid存放路徑,日志存放路徑,配置文件引入,允許生成worker process數等。
2、events塊:配置影響nginx服務器或與用戶的網絡連接。有每個進程的最大連接數,選取哪種事件驅動模型處理連接請求,是否允許同時接受多個網路連接,開啟多個網絡連接序列化等。
3、http塊:可以嵌套多個server,配置代理,緩存,日志定義等絕大多數功能和第三方模塊的配置。如文件引入,mime-type定義,日志自定義,是否使用sendfile傳輸文件,連接超時時間,單連接請求數等。
4、server塊:配置虛擬主機的相關參數,一個http中可以有多個server。
5、location塊:配置請求的路由,以及各種頁面的處理情況
該指令用於匹配 URL。
語法如下:
location [ = | ~ | ~* | ^~] uri { }
(1)= :用於不含正則表達式的 uri 前,要求請求字符串與 uri 嚴格匹配,如果匹配成功,就停止繼續向下搜索並立即處理該請求。
(2)~:用於表示 uri 包含正則表達式,並且區分大小寫。
(3)~*:用於表示 uri 包含正則表達式,並且不區分大小寫。
(4)^~:用於不含正則表達式的 uri 前,要求 Nginx 服務器找到標識 uri 和請求字符串匹配度最高的 location 后,立即使用此 location 處理請求,而不再使用 location 塊中的正則 uri 和請求字符串做匹配。
注意:如果 uri 包含正則表達式,則必須要有 ~ 或者 ~* 標識。
語法規則: 【= | ^~ | ~ | ~* | / | /uri 】 location = /uri = 表示精確匹配,只有完全匹配上才能生效,若找到,停止搜索; location ^~ /uri ^~開頭表示對URL路徑進行前綴匹配,並且在正則匹配之前,若找到,停止搜索; location ~ pattern ~開頭表示區分大小寫的正則匹配,按配置文件順序匹配; location ~* pattern ~*開頭表示不區分大小寫的正則匹配,按配置文件順序匹配; location /uri 不帶任何修飾符,表示前綴匹配,在正則匹配之后; location / 通用匹配,任何未匹配到其他location的請求都會匹配到,相當於default; 多個location配置的情況匹配順序為 首先精確匹配 = ; 其次前綴匹配 ^~; 其次是按照配置文件中的正則匹配; 然后匹配不帶任何修飾符的前綴匹配; 最后交給/通用匹配;
示例
location支持的語法優先級: location匹配順序 # www.abc.com/ 1.location = / { 我是代碼1 } 精確匹配 # www.abc.com/images/ 2.location ^~ /images/ { 我是代碼2 } 匹配常規串,不做正則檢查 # www.abc.com/xxx.gif #www.abc.com/xxx.jpg #www.abc.com/xxx.gif #www.abc.com/xxx.jpeg 3.location ~* \.(gif|jpg|jpeg) { 我是代碼3 } 正則匹配 #優先級為4, www.abc.com/doc/xx資源 4. location /doc/ { 我是代碼4 } 匹配常規字符,有正則優先正則 #如果你誰都沒匹配到的話,默認走/,走網頁根目錄,優先級最低 5.location / { 我是代碼5 } 所有的location都不匹配后,默認匹配
Nginx配置文件位置/usr/local/nginx/conf/nginx.conf
詳解一
[root@localhost conf]# vi nginx.conf #啟動該程序的默認用戶 #user nobody; #一個主進程和多個工作進程。工作進程是單進程的,且不需要特殊授權即可運行;這里定義的是工作進程數量 worker_processes 4; #全局錯誤日志的位置及日志格式 #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { #每個工作進程最大的並發數,設置的工作進程數*每個進程允許的最多線程數就是最大並發數 worker_connections 1024; #http服務器設置 http { #設定mime類型,類型由mime.type文件定義 include mime.types; default_type application/octet-stream; #日志格式 #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #$remote_addr與$http_x_forwarded_for用以記錄客戶端的ip地址; #$remote_user:用來記錄客戶端用戶名稱; #$time_local: 用來記錄訪問時間與時區; #$request: 用來記錄請求的url與http協議; #$status: 用來記錄請求狀態;成功是200, #$body_bytes_sent :記錄發送給客戶端文件主體內容大小; #$http_referer:用來記錄從那個頁面鏈接訪問過來的; #$http_user_agent:記錄客戶瀏覽器的相關信息; #全局訪問日志路徑 #access_log logs/access.log main; #sendfile指令指定 nginx 是否調用sendfile 函數(zero copy 方式)來輸出文件,對於普通應用,必須設為on。如果用來進行下載等應用磁盤IO重負載應用,可設置為off,以平衡磁盤與網絡IO處理速度,降低系統uptime。 sendfile on; #此選項允許或禁止使用socke的TCP_CORK的選項,此選項僅在使用sendfile的時候使用 #tcp_nopush on; #長連接超時時間 #keepalive_timeout 0; keepalive_timeout 65; #開啟壓縮 #gzip on; #配置虛擬主機 server { #虛擬主機使用的端口 listen 80; #虛擬主機域名 server_name localhost; #虛擬主機支持的字符集 #charset koi8-r; #虛擬主機的訪問日志路徑 #access_log logs/host.access.log main; #定義web根路徑 location / { #根目錄路徑 root html; #索引頁 index index.html index.htm; } #404頁面配置 #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # #根據錯誤碼 返回對應的頁面 error_page 500 502 503 504 /50x.html; #定義頁面路徑 location = /50x.html { root html; } #定義反向代理服務器 數據服務器是lamp模型 # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} #定義PHP為本機服務的模型 # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php$ { # root html; # fastcgi_pass 127.0.0.1:9000; # fastcgi_index index.php; # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; # include fastcgi_params; #} # concurs with nginx's one # #location ~ /\.ht { # deny all; #} } # #server { # listen 8000; # listen somename:8080; # server_name somename alias another.alias; # location / { # root html; # index index.html index.htm; # } #} #https的配置方案 # 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; # } #} }
詳解二
########### 每個指令必須有分號結束。################# #user administrator administrators; #配置用戶或者組,默認為nobody nobody。 #worker_processes 2; #允許生成的進程數,默認為1 #pid /nginx/pid/nginx.pid; #指定nginx進程運行文件存放地址 error_log log/error.log debug; #制定日志路徑,級別。這個設置可以放入全局塊,http塊,server塊,級別以此為:debug|info|notice|warn|error|crit|alert|emerg events { accept_mutex on; #設置網路連接序列化,防止驚群現象發生,默認為on multi_accept on; #設置一個進程是否同時接受多個網絡連接,默認為off #use epoll; #事件驅動模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport worker_connections 1024; #最大連接數,默認為512 } http { include mime.types; #文件擴展名與文件類型映射表 default_type application/octet-stream; #默認文件類型,默認為text/plain #access_log off; #取消服務日志 log_format myFormat '$remote_addr–$remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for'; #自定義格式 access_log log/access.log myFormat; #combined為日志格式的默認值 sendfile on; #允許sendfile方式傳輸文件,默認為off,可以在http塊,server塊,location塊。 sendfile_max_chunk 100k; #每個進程每次調用傳輸數量不能大於設定的值,默認為0,即不設上限。 keepalive_timeout 65; #連接超時時間,默認為75s,可以在http,server,location塊。 upstream mysvr { server 127.0.0.1:7878; server 192.168.10.121:3333 backup; #熱備 } error_page 404 https://www.baidu.com; #錯誤頁 server { keepalive_requests 120; #單連接請求上限次數。 listen 4545; #監聽端口 server_name 127.0.0.1; #監聽地址 location ~*^.+$ { #請求的url過濾,正則匹配,~為區分大小寫,~*為不區分大小寫。 #root path; #根目錄 #index vv.txt; #設置默認頁 proxy_pass http://mysvr; #請求轉向mysvr 定義的服務器列表 deny 127.0.0.1; #拒絕的ip allow 172.18.5.54; #允許的ip } } }
上面是nginx的基本配置,需要注意的有以下幾點:
1、1.$remote_addr 與$http_x_forwarded_for 用以記錄客戶端的ip地址; 2.$remote_user :用來記錄客戶端用戶名稱; 3.$time_local : 用來記錄訪問時間與時區;4.$request : 用來記錄請求的url與http協議;
5.$status : 用來記錄請求狀態;成功是200, 6.$body_bytes_s ent :記錄發送給客戶端文件主體內容大小;7.$http_referer :用來記錄從那個頁面鏈接訪問過來的; 8.$http_user_agent :記錄客戶端瀏覽器的相關信息;
2、驚群現象:一個網路連接到來,多個睡眠的進程被同事叫醒,但只有一個進程能獲得鏈接,這樣會影響系統性能。
3、每個指令必須有分號結束。
4、修改user 時要用useradd 添加用戶,創建一個不能從終端登錄的名字為webuser的系統用戶
[root@localhost conf]# useradd -s /sbin/nologin -r webuser
五、nginx的默認網站
當Nginx配置文件中有且只有一個Server的時候,該Server就被Nginx認為是默認網站,所有發給Nginx服務器器80端口的數據都會默認給該Server.
默認網站設置
server { listen 80; server_name localhost; #charset koi8-r; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # #location ~ \.php$ { # root html; # fastcgi_pass 127.0.0.1:9000; # include fastcgi_params; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} }
nginx默認網站的訪問控制
創建環境,在html文件夾里創建abc三個文件分別寫入index.html
[root@localhost html]# ls 50x.html index.html [root@localhost html]# pwd /usr/local/nginx/html [root@localhost html]# mkdir a b c [root@localhost html]# ls 50x.html a b c index.html [root@localhost html]# echo aaa >a/index.html [root@localhost html]# echo bbb >b/index.html [root@localhost html]# echo ccc >c/index.html [root@localhost html]# ls a/ index.html [root@localhost html]# cat a/index.html aaa [root@localhost html]# ls 50x.html a b c index.html [root@localhost html]# elinks http://192.168.199.228/a --dump #本機訪問測試 aaa
用例1 :ip控制
針對a文件夾只允許本機訪問,拒絕其他所有人訪問
設置修改nginx配置文件,本機ip192.168.199.228
[root@localhost html]# pwd /usr/local/nginx/html [root@localhost html]# vi ../conf/nginx.conf ... http{ ... server{ listen 80; server_name localhost; #charset koi8-r; charset utf-8; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; }; #location / 這里的/代表網站的根目錄 #針對a文件夾進行設置; location /a { allow 127.0.0.1; allow 192.168.199.228; deny all; #return 404; #return http://www.jd.com; #可以返回指定錯誤頁,也可以進行url跳轉,注意這里的返回是訪問成功和不成功的都返回 } }
allow
和deny
會按照順序, 從上往下, 找到第一個匹配規則, 判斷是否允許訪問, 所以一般把all
放最后。
其他例子
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
allow 2001:0db8::/32;
deny all;
測試修改后的配置文件是否有誤
[root@localhost html]# pwd /usr/local/nginx/html [root@localhost html]# ../sbin/nginx -g ../conf/nginx.conf nginx: [emerg] unexpected end of parameter, expecting ";" in command line [root@localhost html]#
修改完后方法一:修改完配置一定要檢測Nginx配置是否正確,正確后再重新軟加載配置文件
[root@localhost html]# ../sbin/nginx -t nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful [root@localhost html]# ../sbin/nginx -s reload
修改完后方法二:不再直接kill后再重啟,直接重新加載nginx的配置文件
[root@localhost html]# killall -s HUP nginx [root@localhost html]# elinks http://192.168.199.228/a --dump aaa
用例2:登錄驗證
針對b文件夾,任何人都可以訪問,但是需要憑用戶密碼進行驗證
設置修改nginx配置文件,本機ip192.168.199.228
[root@localhost html]# pwd /usr/local/nginx/html [root@localhost html]# vi ../conf/nginx.conf ... http{ ... server{ listen 80; server_name localhost; #charset koi8-r; charset utf-8; #access_log logs/host.access.log main; location / { root html; index index.html index.htm; }; #location / 這里的/代表網站的根目錄 #針對a文件夾進行設置; location /a { allow 127.0.0.1; allow 192.168.199.228; deny all; #return 404; #return http://www.jd.com; #可以返回指定錯誤頁,也可以進行url跳轉,注意這里的返回是訪問成功和不成功的都返回 } #針對b文件夾進行設置; location /b { auth_basic ”登陸驗證test"; auth_basic_user_file /etc/nginx/htpasswd; #auth_basic_user_file 用來存儲用戶認證信息的文件; } }
語法講解: auth_basic 默認關閉,開啟的話輸入一段字符串即可。 auth_basic_user_file 該文件存儲用戶賬號密碼。
安裝httpd-tools使用htpasswd工具生成認證信息文件放置在上面設置的位置
[root@localhost html]# yum -y install httpd-tools Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile * base: hk.mirrors.thegigabit.com * extras: hk.mirrors.thegigabit.com * updates: hk.mirrors.thegigabit.com ... [root@localhost html]# mkdir /etc/nginx [root@localhost html]# htpasswd -c /etc/nginx/htpasswd user1 #創建文件htpasswd並將新用戶user1和加密的密碼寫入文件到/etc/nginx/目錄下 New password: Re-type new password: Adding password for user user1 [root@localhost html]# htpasswd -m /etc/nginx/htpasswd user2 #如果htpasswd文件已經存在則使用-m參數添加新用戶賬戶密碼 New password: Re-type new password: Adding password for user user2 [root@localhost html]# cat /etc/nginx/htpasswd user1:$apr1$C8hzuJ.t$z8ZI/y4HgrbrhnmC1QkTp/ user2:$apr1$5LB3P1Wj$HxyEELRZ3vDogTGM3xR2E. [root@localhost html]#
重新加載配置文件驗證效果
[root@localhost html]# killall -s HUP nginx [root@localhost html]#
參考鏈接