nginx 基礎入門

2018-10-10 18:55 更新

nginx配置文件:

下載解壓 tar.gz

./configure編譯構(gòu)建

nginx:操作命令 nginx -s stop(快速停止)|quit(優(yōu)雅停止,工作線程完成工作)|reload(重新加載配置文件)|reopen(重新打開日志文件)

quit:以啟動nginx的用戶關閉

reload:主進程接到重載配置文件信號,檢查配置文件合法性,并嘗試應用配置。應用成功后,啟動新的工作進程,并向就的工作進程發(fā)送關閉進程的信號;應用配置失敗,則回滾變化,繼續(xù)使用舊的配置文件。舊的進程接到關閉的命令時,停吃接受新的請求,并繼續(xù)服務當前請求直至結(jié)束,然后停止服務。

kill -s QUIT pid:優(yōu)雅關機

nginx開啟后主機無法訪問虛擬機的nginx解決方案

  1. ping虛擬機,判斷是否防火墻問題

    防火墻問題處理: iptables文件添加 -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT vi /etc/sysconfig/iptables [root@localhost ]# /sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT [root@localhost ]# /etc/init.d/iptables save [root@localhost ]# /etc/init.d/iptables restart

    centos iptables 防火墻:

    禁用防火墻:systemctl disable firewalld

    卸載防火墻:yum remove firewalld -y 使用下面的辦法來恢復原來的習慣,同時解決iptables開機啟動的問題。 yum install iptables-services -y systemctl enable iptables iptables服務會開機啟動,自動從/etc/sysconfig/iptables 文件導入規(guī)則。 為了讓/etc/init.d/iptables save 這條命令生效,執(zhí)行如下: cp /usr/libexec/iptables/iptables.init /etc/init.d/iptables

    nginx代理服務器設置: server { location / { proxy_pass http://localhost:8080/; //80端口下訪問,除了特別定義的location,其它都轉(zhuǎn)發(fā)給8080端口處理

    開啟反向代理緩存,并使用zone name為one的緩存。

    proxy_cache one;
    #設置狀態(tài)碼為200 302過期時間為10分鐘
    proxy_cache_valid  200 302  10m;
    #設置狀態(tài)碼404的過期時間為1分鐘
    proxy_cache_valid  404      1m;

    }

    location ~ .(gif|jpg|png)$ { root /data/images; } }

    nginx反向代理問題: ]:8080 failed (13: Permission denied) while connecting to upstream, 處理: SeLinux 一、關閉SeLinux 查看SELinux狀態(tài): 1、/usr/sbin/sestatus -v ##如果SELinux status參數(shù)為enabled即為開啟狀態(tài) SELinux status: enabled 2、getenforce ##也可以用這個命令檢查 關閉SELinux: 1、臨時關閉(不用重啟機器): setenforce 0 ##設置SELinux 成為permissive模式

    setenforce 1 設置SELinux 成為enforcing模式

    2、修改配置文件需要重啟機器: 修改/etc/selinux/config 文件 將SELINUX=enforcing改為SELINUX=disabled 重啟機器即可 二、執(zhí)行下面的命令 setsebool -P httpd_can_network_connect 1

    連接處理方法配置: --with-select_module:配置使用select --with-poll_module:配置使用poll linux2.6+:epoll

    查看nginx 配置信息:安裝使用配置-- [root@zookeeper nginx]# nginx -V nginx version: nginx/1.12.2 built by gcc 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC) built with OpenSSL 1.0.2k-fips 26 Jan 2017 TLS SNI support enabled configure arguments: --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/run/nginx.pid --lock-path=/run/lock/subsys/nginx --user=nginx --group=nginx --with-file-aio --with-ipv6 --with-http_auth_request_module --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --with-http_geoip_module=dynamic --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_slice_module --with-http_stub_status_module --with-http_perl_module=dynamic --with-mail=dynamic --with-mail_ssl_module --with-pcre --with-pcre-jit --with-stream=dynamic --with-stream_ssl_module --with-google_perftools_module --with-debug --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic' --with-ld-opt='-Wl,-z,relro -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -Wl,-E'

    配置日志級別: error_log /var/log/nginx/error.log debug; // debug,info,notice,warn,error,crit, or alert

    測試配置文件合法性:nginx -t

    loadblance:

    round-robin:輪詢,可以配置權重,默認策略,服務器性能均衡,不可以直接配置

    least-connected:least_conn、最少連接

    ip-hash:ip作為hask key,選擇服務器,保障統(tǒng)一客戶端能請求總是到達同一服務器

    hash $request_uri:按請求url hash值分配服務器

    least_time:最少平均延遲和最少活躍連接。

    負載均衡: max_fails(默認1,一次無回復,則nginx認定服務器down), fail_timeout(默認10s,nginx標記服務器下線后,經(jīng)過時間間隔后認定服務器down), and slow_start只對對服務器起作用 http{ ... upstream upblance { ip_hash; // ip_hash | least_conn | least_time server 192.168.126.128:8080 max_conns=2; //round-robin策略下,可配置 weight=2,權重;max_conns服務器最大連接數(shù),超過,則將請求置于請求隊列,超過隊列大小,則報錯 server localhost:8080; // 添加 backup 設置為備用服務器;添加down 暫時下線服務器;slow_start=30s慢啟動,用戶剛恢復的服務器; queue 100 timeout=70; //1.15.12版本及之后 }

    server{ ...
    location / { proxy_pass http://upblance; //http必須 }

    配置https server:可以使用openssl 生成相應的免費證書 server.key server.crt server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; servername ; root /usr/share/nginx/html;

    ssl_certificate "server.crt"; ssl_certificate_key "server.key"; ssl_session_cache shared:SSL:1m; ssl_session_timeout 10m; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on;

    Load configuration files for the default server block.

    include /etc/nginx/default.d/*.conf;

    location / { }

    error_page 404 /404.html; location = /40x.html { }

    error_page 500 502 503 504 /50x.html; location = /50x.html { } }

    rewrite,重定向:定義一個新的server,重新指向 server { listen 80; server_name test.com; return 301 http://www.test.com$request_uri; //指向下面server

    }

    server { listen 80 default_server; listen [::]:80 default_server; server_name www.test.com; ... ...

    one should simply define example.com, www.example.com, and “everything else”: server { listen 80; server_name example.comwww.example.com; ... }

    server { listen 80 default_server; servername ; //指代所有其它 return 301 http://example.com$request_uri; }

    websocket:101 switch protocal location /chat/ { proxy_pass http://192.168.7.133:8888/websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; // proxy_set_header Connection "upgrade"; // }

    libxml2 + libxml2-devel

    fastcgi:網(wǎng)關轉(zhuǎn)發(fā)請求 示例,處理php請求:linux安裝php-fpm fastcgi軟件 location ~ .php$ { root html; fastcgi_pass localhost:9000; fastcgi_index index.php; include fastcgi.conf; //必要的配置 }

    session持久化: upstream:ip_hash、hash、sticky 。。。

    四層協(xié)議的轉(zhuǎn)發(fā)、代理或者負載均衡:stream模塊,平行 http stream { upstream streamhost { server 192.168.7.133:9090; }

    server{ listen 9090; proxy_pass streamhost; proxy_timeout 3s; proxy_connect_timeout 1s; } }

    訪問控制: location / { deny 192.168.1.1; allow 192.168.1.0/24; allow 10.1.1.0/16; allow 2001:0db8::/32; deny all; } location / { proxy_pass http://upblance; deny 192.168.126.1; // address | CIDR | unix: | all;deny: Denies access for the specified network or address;allow: Allows access for the specified network or address. }

    重新載入nginx配置文件是報錯:nginx: [error] invalid PID number "" in "/run/nginx.pid"

    解決:重新制定配置文件位置,然后再載入配置文件

    nginx -c 路徑/nginx.conf

    nginx -s reload

    nginx ssi:

    。。。

    with-http_addition_module:相應前后添加內(nèi)容:

    location / { proxy_pass http://upblance;

    deny 192.168.126.1;

        add_before_body /header/;
        add_after_body /footer/;
    }
    location /header/
    {
        root /usr/share/nginx/html;

    } location /footer/ { root /usr/share/nginx/html;

    }

    autoindex on:當請求資源目錄下沒有index時,自動展現(xiàn)目錄下文件列表: location /autoindex/ { autoindex on; autoindex_exact_size on; autoindex_localtime on; root /usr/share/nginx/html; }

    random_index on: 隨機返回請求資源目錄下資源: location /randomindex/ { random_index on; root /usr/share/nginx/html; }

    gzip壓縮:* ngx_http_gzip_module 實時壓縮,每次讀取資源壓縮

    gzip on; //啟動壓縮 gzip_min_length 1000; //需要壓縮的最小長度,取自于 Content-Length” gzip_comp_level 6; //壓縮比率,越大耗費的cpu越多 gzip_proxied expired no-cache no-store private auth; //根據(jù)請求和回復,決定是否啟用代理壓縮 gzip_types text/plain application/xml; //針對壓縮的資源類型 gzip_disable "MSIE [1-6]."; //根據(jù)客戶端 User-Agent進行設置,MSIE[1-6]微軟1-6版本瀏覽器,或者基于微軟瀏覽器內(nèi)核的瀏覽器; //The special mask “msie6” (0.7.12) corresponds to the regular expression “MSIE [4-6].”, but works faster

rewrite==ngx_http_rewrite_module: rewrite regex replacement [flag]; rewrite /rewrite /; //路徑包含rewrite的請求 rewrite /rewrite / permanent; // permanent 創(chuàng)建永久重定向301規(guī)則,重定向新的url,(瀏覽器更新書簽、爬蟲更新抓取內(nèi)容)

rewrite ^/rewrite$ /; //嚴格的路徑重定向 rewrite /rewrite/(.*) http://www.$1.com; //重定向路徑包含http https,則直接重定向至replacement url;/rewrite/baidu =》http://www.baidu.com

flag: last:停止當前指令集,搜索與更改后的URI匹配的location brak:停止當前指令集 redirect:302臨時重定向 permanent:301永久重定向

last 和 break一樣 它們都會終止此 location 中其他它rewrite模塊指令的執(zhí)行, 但是 last 立即發(fā)起新一輪的 location 匹配 而 break 則不會。

  • last – Stops execution of the rewrite directives in the current server or location context, but NGINX Plus searches for locations that match the rewritten URI, and any rewritedirectives in the new location are applied (meaning the URI can be changed again).
  • break – Like the break directive, stops processing of rewrite directives in the current context and cancels the search for locations that match the new URI. The rewrite directives in the new location are not executed.

    重新后之前的請求參數(shù)會附加到新的url之后;在新的url之后添加 ?, 則拋棄之前的參數(shù)。 GET /rewrite/baidu?time=time() =》https://www.baidu.com/?time=time()

    log參數(shù):

自定義log profile:

同時也可以針對不同的server定義不同的 error 和 access log log_format test '$remote_addr - [$time_local] "$request" $status '; //日志標識 ... ... server { access_log /var/log/nginx/root.log test; //使用自定義的日志 profile }

log文件fd緩存: http{ open_log_file_cache max=1000 inactive=20s min_uses=2 valid=1m; //緩存打開的日志文件描述符 ....

限流:ngx_http_limit_req_module 限制請求處理速率,尤其是源自同一ip的請求:基于漏桶方法 http { limit_req_zone $binary_remote_addr zone=first:10m rate=1r/s; //定義 key為請求地址, zone名為first,容量為10m的共享內(nèi)存區(qū)域(lru),處理速率限制為每秒1次。 limit_req_zone $server_name zone=perserver:10m rate=10r/s; //定義key為服務器名稱,zone為perserver,容量為10m的共享內(nèi)存區(qū)域(lru),處理速率限制為每秒10次。 ...

server {

...

location /search/ { limit_req zone=first burst=5; //使用共享內(nèi)存區(qū)域first,設定爆發(fā)請求數(shù)不超過5,如果不希望延遲過量的請求,則尾部添加nodelay標識 limit_req zone=perserver burst=10; //多限制共存,并 }

如下:error log: 2018/07/20 03:03:40 [error] 9969#0: 714 limiting requests, excess: 5.213 by zone "first", client: 192.168.126.1, server: www.test.com, request: "GET / HTTP/1.1", host: "192.168.126.129" 2018/07/20 03:03:40 [error] 9969#0: 714 limiting requests, excess: 5.013 by zone "first", client: 192.168.126.1, server: www.test.com, request: "GET / HTTP/1.1", host: "192.168.126.129" 2018/07/20 03:03:41 [error] 9969#0: *715 limiting requests, excess: 5.037 by zone "first", client: 192.168.126.1, server: www.test.com, request: "GET / HTTP/1.1", host: "192.168.126.129

限制下載速率: location /randomindex/ { random_index on; root /usr/share/nginx/html; limit_rate_after 1m; //下載1m后開始限速 limit_rate 100k; //限制下載速率為1k/s }

鑒權ngx_http_auth_basic_module:用于保護特定url連接安全;針對不同的url可以生成不同的鑒權文件。

location / { proxy_pass http://upblance;

deny 192.168.126.1;

        add_before_body /header/;
        add_after_body /footer/;
        limit_req zone=first burst=5;
        auth_basic           "default n";
        auth_basic_user_file /etc/nginx/htpasswd; //鑒權文件
    }

使用httpd-tools生成鑒權文件: [root@zookeeper nginx]# yum install httpd-tools //安裝加密工具 [root@zookeeper nginx]# htpasswd –c /etc/nginx/htpasswd roger //生成用戶名為roger的密碼,并存放于文件/etc/nginx/htpasswd 文件中 [root@zookeeper nginx]# cat htpasswd roger:$apr1$c94VlRcs$fuU12rxXOVfxGNn8vGr8E //文件格式

防盜鏈,安全連接:ngx_http_secure_link_module: secure_link_secret:/prefix/hash/link location /securelink/ { root html; secure_link_secret test_secure; //用于檢驗請求連接, if ($secure_link = "") { //如果請求連接包含權限驗證信息,則真正的請求會從請求連接分離出來存入$scure_link,否則的話置空 return 403; } rewrite ^ /securelink/$secure_link break; //break 必要 }

生成MD5 HASH: 請求資源/secure.html [root@zookeeper nginx]# echo -n 'secure.htmltest_secure' | openssl dgst -md5 (stdin)= 6da8690e402cd3b50da5d751d13b4ea8 生成請求連接: /securelink/secure.html http://192.168.126.129/securelink/6da8690e402cd3b50da5d751d13b4ea8/secure.html

secure_link、secure_link_md5: location /securelinkx { root html; secure_link $arg_md5,$arg_expires; //參數(shù) md5、expires secure_link_md5 "$secure_link_expires$uri$remote_addr secure_test"; //secure_link_expires:用于內(nèi)部獲取expires;uri:請求路徑;secure_test:添加的密參;remote_addr:注意獲取的值;自選需要的參數(shù) if ($secure_link = "") { return 403; }

if ($secure_link = "0") { return 410; } } 請求路徑:/securelinkx/ md5: [root@zookeeper nginx]# echo -n '2147483647/securelinkx/192.168.126.1 securetest' | openssl md5 -binary | openssl base64 | tr +/ - | tr -d = Qia1rWs8Xx2ZZkkJ7I4_IQ 請求連接: http://192.168.126.129/securelinkx/?md5=Qia1rWs8Xx2ZZkkJ7I4_IQ&expires=2147483647

配置fastcgi wordpress: location /wordpress { root /var/www; fastcgi_pass localhost:9000; fastcgi_index index.php; include fastcgi.conf; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; }

靜態(tài)文件提前壓縮: http_gzip_static_module,直接讀取壓縮的資源 .gz格式, location ~ .(jpg|png|jpeg|bmp|gif|swf)$ { gzip_static on; root /usr/share/nginx/html/images; expires 1d; }

sub_filter: http_sub_module location / { sub_filter 'href="http://127.0.0.1:8080/' 'href="https://$host/'; sub_filter 'img src="http://127.0.0.1:8080/' 'img src="https://$host/'; sub_filter_once on; }

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號