Nginx-基础使用
Nginx (engine x) 是一個高性能的HTTP和反向代理web服務器,同時也提供了IMAP/POP3/SMTP服務。
常用場景
- 靜態資源服務器
- 代理服務
- 跨站資源訪問
- 適配PC與移動端環境
- 負載均衡調度
- 緩存服務
- 簡單的訪問控制
- 圖片處理
默認配置文件
全局塊:nginx 全局配置。比如用戶以及用戶組 user,nginx 進程 pid 文件存放路徑,日志存放路徑 error_log,工作進程worker process 數等,也可以引入配置文件。
events 塊:服務器連接相關配置。比如進程的最大連接數,選取哪種事件驅動模型處理連接請求,是否允許同時接受多個網路連接,開啟多個網絡連接序列化等。
http 塊:可嵌套多個虛擬主機 server,配置代理,設置緩存,配置日志定義等。支持很多第三方模塊的配置。比如文件引入,mime-type 定義,圖片壓縮,日志自定義,傳輸文件配置,設置連接超時時間,單個連接請求數等等。
server 塊:虛擬主機的相關配置。
location 塊:請求的路由相關配置,特殊頁面的處理。
# {全局塊}# 設置用戶組 #user nobody; # 配置用戶或者組,默認為nobody nobody。 #user admin admin; # 設置工作進程的數量 worker_processes 1;# 指定日志路徑,日志級別包括 debug | info | notice | warn | error | alert 等 #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info;# 指定進程文件 #pid logs/nginx.pid;events { # {event塊}# 設置一個進程是否同時接受多個網絡連接,默認為off#multi_accept on;# 事件驅動模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport#use epoll;# 進程的最大連接數worker_connections 1024; }http { {#http塊}# 文件拓展名查找集合include mime.types;# 默認文件類型為文件流,匹配.*default_type application/octet-stream;# 日志格式定義,main為日志別名#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 off;# 指定日志輸入文件#access_log logs/access.log main;# 調用 sendfile 系統傳輸文件,sendfile on 表示通過文件描述符直接拷貝,而不是用read()/write()sendfile on;# tcp_nopush = on 會設置調用tcp_cork方法,這個也是默認的,結果就是數據包不會馬上傳送出去,等到數據包最大時,一次性的傳輸出去,這樣有助于解決網絡堵塞。#tcp_nopush on;# 設置連接超時時間#keepalive_timeout 0;keepalive_timeout 65;# 是否啟用 gzip 壓縮,需要瀏覽器支持,需要解壓縮#gzip on;# 設置gzip所需的http協議最低版本 (HTTP/1.1, HTTP/1.0)#gzip_http_version 1.1;# 設置壓縮級別,壓縮級別越高壓縮時間越長 (1-9)#gzip_comp_level 4;# 設置壓縮的最小字節數, 頁面Content-Length獲取#gzip_min_length 1000;# 設置壓縮文件的類型#gzip_types text/plain application/javascript text/css;server { #{server塊}# 監聽端口listen 80;# 虛擬主機名稱server_name localhost;# 設置編碼字符集#charset koi8-r;# 指定日志輸入文件#access_log logs/host.access.log main;# 監聽請求路由location / { #{location塊}# 查找根目錄root html;# 默認匹配index index.html index.htm;}#error_page 404 /404.html;# redirect server error pages to the static page /50x.html# 重定位服務器錯誤到靜態頁面 /50x.htmlerror_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;# fastcgi_index index.php;# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;# include fastcgi_params;#}# deny access to .htaccess files, if Apache's document root# concurs with nginx's one##location ~ /\.ht {# deny all;#}}# another virtual host using mix of IP-, name-, and port-based configuration##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;# }#}} 復制代碼nginx 內置變量
- $args : #這個變量等于請求行中的參數,同 query_string
- $content_length : 請求頭中的 Content-length 字段。
- $content_type : 請求頭中的 Content-Type 字段。
- $document_root : 當前請求在 root 指令中指定的值。
- $host : 請求主機頭字段,否則為服務器名稱。
- $http_user_agent : 客戶端 agent 信息
- $http_cookie : 客戶端 cookie 信息
- $limit_rate : 這個變量可以限制連接速率。
- $request_method : 客戶端請求的動作,通常為 GET 或 POST。
- $remote_addr : 客戶端的 IP 地址。
- $remote_port : 客戶端的端口。
- $remote_user : 已經經過 Auth Basic Module 驗證的用戶名。
- $request_filename : 當前請求的文件路徑,由 root 或 alias 指令與 URI 請求生成。
- $scheme : HTTP 方法(如 http ,https)。
- $server_protocol : 請求使用的協議,通常是 HTTP/1.0 或 HTTP/1.1。
- $server_addr : 服務器地址,在完成一次系統調用后可以確定這個值。
- $server_name : 服務器名稱。
- $server_port : 請求到達服務器的端口號。
- $request_uri : 包含請求參數的原始URI,不包含主機名,如:”/foo/bar.php?arg=baz”。
- $uri :不帶請求參數的當前 URI,$uri 不包含主機名,如”/foo/bar.html”。
- $document_uri : 與 $uri 相同
nginx 基本命令
- nginx -t 檢查配置文件是否有語法錯誤
- nginx -s reload 向主進程發送信號,重新加載配置文件
- nginx -s stop 快速關閉
- nginx -s quit 等待工作進程處理完成后關閉
location 匹配規則(優先級遞減)
| = | 進行普通字符精確匹配。也就是完全匹配 |
| ^~ | 前綴匹配。如果匹配成功,則不再匹配其他location |
| v~ | 表示執行一個正則匹配,區分大小寫 |
| ~* | 表示執行一個正則匹配,不區分大小寫 |
| /xxx/ | 常規字符串路徑匹配 |
| / | 通用匹配,任何請求都會匹配到 |
靜態資源服務器
常見的靜態資源包括圖片,文檔,視頻等文件,所以 nginx 常用來作為靜態網站服務器,或者作為 cdn 資源服務器。 例如以下是一個前后端分離的工程的前端工程部署配置:
... server {...listen 8080;server_name localhost;root html/project;location / {// 按照優先級 '$uri' > '$uri/' > '/index.html' > '=404'依次匹配try_files $uri $uri/ /index.html =404;index index.html index.htm;} } 復制代碼代理服務
nginx 用作代理服務器可以作為正向代理或者反向代理,而反向代理正是跨站資源訪問的解決方案之一。 如下是正向代理配置:
... server {...listen 8080;server_name localhost;# DNS 域名解析服務器resolver 8.8.8.8;# 解析超時時間resolver_timeout 5s;location / {proxy_pass $scheme://$http_host/$request_uri;proxy_set_header Host $http_host;proxy_buffers 256 4k;proxy_max_temp_file_size 0;proxy_connect_timeout 30;proxy_cache_valid 200 302 10m;proxy_cache_valid 301 1h;proxy_cache_valid any 1m;} } 復制代碼一次代理,直接在shell執行:
export http_proxy=http://x.x.x.x:8080 復制代碼永久使用:
vim ~/.bashrc export http_proxy=http://x.x.x.x:8080 source .bashrc # 刷新以加載變量 復制代碼跨站資源訪問
反向代理配置如下:
... server {...listen 80;server_name localhost;location /api {# 代理轉發proxy_pass http://localhost:8081;# 路徑重寫(如果需要)# rewrite /api/(.*) /$1 break;# 請求host傳給后端proxy_set_header Host $http_host;# 設置用戶ip地址proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $remote_addr;proxy_buffers 256 4k;proxy_max_temp_file_size 0;# 代理超時時間proxy_connect_timeout 30;# 當請求服務器出錯去尋找其他服務器proxy_next_upstream error timeout invalid_header http_500 http_502 http_503; }} 復制代碼適配PC與移動端環境
nginx 可以通過內置變量 $http_user_agent,獲取到請求客戶端的 userAgent,從而知道用戶處于移動端還是PC,進而控制重定向到H5站還是PC站。
... server {...listen 80;server_name localhost;location / {# 移動、pc設備適配if ($http_user_agent ~* '(Android|webOS|iPhone|iPod|BlackBerry)') {set $mobile_request '1';}if ($mobile_request = '1') {rewrite ^.+ http://mysite-base-H5.com;}} } 復制代碼負載均衡調度
RR(round robin:輪詢)
... server {...upstream web_servers { server localhost:8081; server localhost:8082; }server {...listen 80;server_name localhost;#access_log logs/host.access.log main;location / {proxy_pass http://web_servers;# 必須指定Header Hostproxy_set_header Host $host:$server_port;}} } 復制代碼按權重分配
upstream test {server localhost:8081 weight=1;server localhost:8082 weight=3;server localhost:8083 weight=4 backup; } 復制代碼按地址分配:ip_hash
upstream test {ip_hash;server localhost:8080;server localhost:8081; } 復制代碼后端服務器的響應時間來分配:fair(第三方)
upstream backend {fair;server localhost:8080;server localhost:8081; } 復制代碼按訪問url的hash結果來分配:url_hash(第三方)
upstream backend {hash $request_uri;hash_method crc32;server localhost:8080;server localhost:8081; } 復制代碼緩存服務
對擴展名為 gif,jpg,jpeg,png,bmp,swf,js,css 的圖片,flash,javascript,css 文件開啟 Web 緩存,其他文件不緩存。配置文件如下:
user www; worker_processes 8;events {worker_connections 65535; }http {include mime.types;default_type application/octet-stream;charset utf-8;log_format main '$http_x_forwarded_for $remote_addr $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_cookie" $host $request_time';sendfile on;tcp_nopush on;tcp_nodelay on;keepalive_timeout 65;#要想開啟nginx的緩存功能,需要添加此處的兩行內容!#設置Web緩存區名稱為cache_one,內存緩存空間大小為500M,緩存的數據超過1天沒有被訪問就自動清除;訪問的緩存數據,硬盤緩存空間大小為30Gproxy_cache_path /usr/local/nginx/proxy_cache_path levels=1:2 keys_zone=cache_one:500m inactive=1d max_size=30g;#創建緩存的時候可能生成一些臨時文件存放的位置proxy_temp_path /usr/local/nginx/proxy_temp_path;fastcgi_connect_timeout 3000;fastcgi_send_timeout 3000;fastcgi_read_timeout 3000;fastcgi_buffer_size 256k;fastcgi_buffers 8 256k;fastcgi_busy_buffers_size 256k;fastcgi_temp_file_write_size 256k;fastcgi_intercept_errors on;client_header_timeout 600s;client_body_timeout 600s;client_max_body_size 100m; client_body_buffer_size 256k; gzip on;gzip_min_length 1k;gzip_buffers 4 16k;gzip_http_version 1.1;gzip_comp_level 9;gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php;gzip_vary on;upstream LB-WWW {ip_hash;server 192.168.1.101:80 max_fails=3 fail_timeout=30s; #max_fails = 3 為允許失敗的次數,默認值為1server 192.168.1.102:80 max_fails=3 fail_timeout=30s; #fail_timeout = 30s 當max_fails次失敗后,暫停將請求分發到該后端服務器的時間server 192.168.1.118:80 max_fails=3 fail_timeout=30s;}server {listen 80;server_name www.wangshibo.com;index index.html index.php index.htm;root /var/www/html;access_log /usr/local/nginx/logs/www-access.log main;error_log /usr/local/nginx/logs/www-error.log;location / {proxy_pass http://LB-WWW;proxy_redirect off ;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header REMOTE-HOST $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;#跟后端服務器連接超時時間,發起握手等候響應時間proxy_connect_timeout 300;#后端服務器回傳時間,就是在規定時間內后端服務器必須傳完所有數據proxy_send_timeout 300;#連接成功后等待后端服務器的響應時間,已經進入后端的排隊之中等候處理proxy_read_timeout 600;#代理請求緩沖區,會保存用戶的頭信息以供nginx進行處理proxy_buffer_size 256k;#同上,告訴nginx保存單個用幾個buffer最大用多少空間proxy_buffers 4 256k;#如果系統很忙時候可以申請最大的proxy_buffersproxy_busy_buffers_size 256k;#proxy緩存臨時文件的大小proxy_temp_file_write_size 256k;proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;proxy_max_temp_file_size 128m;}location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|js|css)$ { #使用Web緩存區cache_one,已在nginx.conf的緩存配置中命名的。proxy_cache cache_one ;#對不同HTTP狀態碼緩存設置不同的緩存時間proxy_cache_valid 200 304 12h ;proxy_cache_valid 301 302 1m ;proxy_cache_valid any 1m ;#設置Web緩存的Key值,Nginx根據Key值md5哈希存儲緩存,這里根據"域名,URI,#參數"組合成Keyproxy_cache_key $host$uri$is_args$args;}#用于清除緩存的url設置#假設一個URL為http://www.wangshibo.com/test.gif,那么就可以通過訪問http://www.wangshibo.com/purge/test.gif清除該URL的緩存。location ~ /purge(/.*) {#設置只允許指定的IP或IP段才可以清除URL緩存allow 127.0.0.1 ;allow 192.168.0.0/16 ;deny all ;proxy_cache_purge cache_one $host$1$is_args$args ;}} } 復制代碼簡單的訪問控制
deny 和 allow 是 ngx_http_access_module 模塊(已內置)中的語法。采用的是從上到下匹配方式,匹配到就跳出不再繼續匹配。上述配置的意思就是,首先禁止 192.168.1.100 訪問,然后允許 192.168.1.10-200 ip段內的訪問(排除 192.168.1.100),同時允許 10.110.50.16 這個單獨ip的訪問,剩下未匹配到的全部禁止訪問。實際生產中,經常和 ngx_http_geo_module 模塊(可以更好地管理ip地址表,已內置)配合使用。
... server {...location / {deny 192.168.1.100;allow 192.168.1.10/200;allow 10.110.50.16;deny all;} } 復制代碼圖片處理
滿足日常對圖片的裁剪/縮放/旋轉/圖片品質等處理需求。要用到 ngx_http_image_filter_module 模塊。這個模塊是非基本模塊,需要安裝。 下面是圖片縮放功能部分的 nginx 配置:
... server {...# 圖片縮放處理# 這里約定的圖片處理url格式:以 mysite-base.com/img/路徑訪問location ~* /img/(.+)$ {#圖片服務端儲存地址alias /Users/cc/Desktop/server/static/image/$1;#圖片寬度默認值set $width -;#圖片高度默認值set $height -;if ($arg_width != "") {set $width $arg_width;}if ($arg_height != "") {set $height $arg_height;}#設置圖片寬高image_filter resize $width $height;#設置Nginx讀取圖片的最大bufferimage_filter_buffer 10M;#是否開啟圖片圖像隔行掃描image_filter_interlace on;#圖片處理錯誤提示圖,例如縮放參數不是數字error_page 415 = 415.png; } } 復制代碼參考網站以及文章
nginx官網
Nginx與前端開發
前端想要了解的Nginx
Nginx常見使用場景-WEB服務(四)
nginx應用場景
Nginx 之六: Nginx服務器的正向及反向代理功能
nginx之正向代理
nginx的web緩存服務環境部署記錄
總結
以上是生活随笔為你收集整理的Nginx-基础使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: GMQ稳定币为区块链资产在金融市场的进一
- 下一篇: Nginx 0day LDAP RCE