nginx 詳解 - 詳細配置說明

本文爲看視頻《Nginx入門到實踐》總結的學習筆記。php

1、服務器基礎配置

遠程連接服務器

ssh 用戶名@公網ip
複製代碼

默認的用戶名是root,假如公網 ip 是 a.b.c.d, 那連接命名就是html

ssh root@a.b.c.d
複製代碼

下載安裝基礎庫

yum -y install gcc gcc-c++ autoconf pcre pcre-devel make automake
yum -y install wget httpd-tools vim
複製代碼

關閉 iptables

查看iptables規則前端

iptables -L
或
iptables -t nat -L
複製代碼

關閉 iptables 規則java

iptables -F
或
iptables -t nat -F
複製代碼

關閉 SELinux

查看是否打開node

getenforce
複製代碼

關閉linux

setenforce 0
複製代碼

2、Nginx 簡介及安裝

Nginx 是一個開源且高性能、高可靠的 HTTP 中間件、代理服務。nginx

安裝Nginx

打開官網 nginx.org/en/linux_pa…c++

To set up the yum repository for RHEL/CentOS, create the file named /etc/yum.repos.d/nginx.repo with the following contents:git

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/OS/OSRELEASE/$basearch/
gpgcheck=0
enabled=1
複製代碼

Replace 「OS」 with 「rhel」 or 「centos」, depending on the distribution used, and 「OSRELEASE」 with 「6」 or 「7」, for 6.x or 7.x versions, respectively.程序員

3、安裝目錄及配置講解

3.1 安裝目錄講解

查看nginx的全部安裝目錄

rpm -ql nginx
複製代碼

而後獲得以下配置

[root@ ~]# rpm -ql nginx

nginx日誌輪轉,用於logrotate服務的日誌切割
/etc/logrotate.d/nginx

nginx主配置文件
/etc/nginx/nginx.conf
/etc/nginx
/etc/nginx/conf.d
/etc/nginx/conf.d/default.conf

cgi配置相關,fastcgi配置
/etc/nginx/fastcgi_params
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params

編碼轉換映射轉化文件
/etc/nginx/koi-utf
/etc/nginx/koi-win
/etc/nginx/win-utf

設置http協議的 Content-Type 與擴展名對應關係
/etc/nginx/mime.types


用於配置出系統守護進程管理器管理方式
/etc/sysconfig/nginx
/etc/sysconfig/nginx-debug
/usr/lib/systemd/system/nginx-debug.service
/usr/lib/systemd/system/nginx.service

nginx模塊目錄
/etc/nginx/modules
/usr/lib64/nginx/modules


/usr/lib64/nginx

/usr/libexec/initscripts/legacy-actions/nginx
/usr/libexec/initscripts/legacy-actions/nginx/check-reload
/usr/libexec/initscripts/legacy-actions/nginx/upgrade

nginx服務的啓動管理的終端命令
/usr/sbin/nginx
/usr/sbin/nginx-debug

nginx的手冊和幫助文件
/usr/share/doc/nginx-1.14.0
/usr/share/doc/nginx-1.14.0/COPYRIGHT
/usr/share/man/man8/nginx.8.gz


/usr/share/nginx
/usr/share/nginx/html
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/index.html

nginx 的緩存目錄
/var/cache/nginx

nginx日誌目錄
/var/log/nginx
複製代碼

3.2 安裝編譯參數

命令 nginx -V 查看全部編譯參數

3.3 Nginx 默認配置語法

參數 說明
user 設置nginx服務的系統使用用戶
worker_processes 工做進程數(通常與服務器核數保持一致)
rror_log nginx的錯誤日誌
pid nginx服務啓動時候pid
events -> worker_connections 每一個進程容許最大鏈接數
events -> use 工做進程數

nginx 的默認配置文件

文件路徑 /etc/nginx/conf.d/default.conf

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log /var/log/nginx/host.access.log main;

    location / {
        root   /usr/share/nginx/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   /usr/share/nginx/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;
    #}
}
複製代碼

能夠去 /usr/share/nginx/html/index.html 修改默認的展現頁面,也能夠去 /usr/share/nginx/html/50x.html 修改錯誤頁面。

修改後重啓 nginx

systemctl reload nginx.service
或
systemctl restart nginx.service
複製代碼

檢查 nginx 配置,結果出現 successful 表示成功

nginx -t -c /etc/nginx/nginx.conf
複製代碼

從新加載配置

nginx -s reload -c /etc/nginx/nginx.conf
複製代碼

4、常見 Nginx 中間架構

  1. 靜態資源WEB服務
  2. 代理服務
  3. 負載均衡調度器 SLB
  4. 動態緩存

4.1 靜態資源WEB服務

配置語法-文件讀取

Syntax: sendfile on|off;
Default: sendfile off;
Context: http,server,location,if in location
複製代碼

引讀:--with-file-aio 異步文件讀取

配置語法- tcp_nopush

Syntax: tcp_nopush on|off;
Default: tcp_nopush off;
Context: http,server,location
複製代碼

配置語法- tcp_nodelay

Syntax: tcp_nodelay on|off;
Default: tcp_nodelay on;
Context: http,server,location
複製代碼

配置語法- 壓縮

Syntax: gzip_comp_level level;
Default: gzip_comp_level 1;
Context: http,server,location
複製代碼
Syntax: gzip_http_version 1.0|1.1;
Default: gzip_http_version 1.1;
Context: http,server,location
複製代碼

擴展 Nginx 壓縮模塊

預讀 gzip 功能
http_gzip_static_module

應用支持 gunzip 的壓縮方式
http_gunzip_module
複製代碼

瀏覽器緩存設置

配置語法 - expires

添加 Cache-Control、Expires 頭

Syntax:expires [modified] time;
		expires epoch | max | off
Default: expires off;
Context: http, server, location, if in location
複製代碼

跨域

*表示容許全部的網站跨域,爲了安全起見能夠設置僅須要的網址

location ~ .*\.(htm|html)$ {
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
    root /opt/app/code
}
複製代碼

基於 http_refer 防盜鏈配置模塊

Syntax: valid_referers none | blocked | server_names | string...;
Default: -
Context: server, location,
複製代碼

4.2 代理服務

正向代理與反向代理的區別在於代理的對象不同

  • 正向代理代理的對象是客戶端

  • 反向代理代理的對象是服務端

配置語法

Syntax: proxy_pass URL
Default: -
Context: location,if in location,limit_except
複製代碼

URL 通常是如下三種

http://localhost:8080/uri/
https://192.168.1.1:8000/uri/
http://unix:/tmp/backend.socket:/uri/;
複製代碼

4.3 負載均衡

HttpIndex模塊

這個模塊提供一個簡單方法來實如今輪詢和客戶端IP之間的後端服務器負荷平衡。

配置範例:

resolver 10.0.0.1;

upstream dynamic {
    zone upstream_dynamic 64k;
    
    hash $request_uri;  #按照url的hash值來分配,同一個url分配到同一個服務器

    server backend1.example.com      weight=5;
    server backend2.example.com:8080 fail_timeout=5s slow_start=30s;
    server 192.0.2.1                 max_fails=3;
    server backend3.example.com      resolve;
    server backend4.example.com      service=http resolve;

    server backup1.example.com:8080  backup;
    server backup2.example.com:8080  backup;
}

server {
    location / {
        proxy_pass http://dynamic;
        health_check;
    }
}
複製代碼

狀態解釋

配置 說明
down 當前的server暫時不參與負載均衡
backup 預留的備份服務器
max_fails 容許請求失敗的次數
fail_timeout 通過max_fails 失敗後,服務暫停的時間
max_conns 限制最大的接收的鏈接數

調度算法

配置 說明
輪詢 按時間順序逐一分配到不停的後端服務器
加權輪詢 weight值越大,分配到的訪問概率越高
ip_hash 每一個請求按照訪問IP的hash結果分配,這樣來自同一個ip固定訪問一個後端服務器
url_hash 按照訪問的URL的hash結果來分配請求,使每一個URL定向到同一個後端服務器
least_conn 最少鏈接數,哪一個機器鏈接數少就分發
hash關鍵數值 hash自定義的key

4.4 緩存

緩存類型分類:客戶端緩存,代理緩存,服務端緩存

proxy_cache

Syntax:	proxy_cache zone | off;
Default:	
proxy_cache off;
Context:	http, server, location
複製代碼

proxy_cache_path

Syntax:	proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];
Default:	—
Context:	http
複製代碼

實例

proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=cache_zone:10m max_size=10g inactive=60m use_temp_path=off;

map $request_method $purge_method {
    PURGE   1;
    default 0;
}

server {
    ...
    location / {
        proxy_pass http://backend;
        proxy_cache cache_zone;
        proxy_cache_key $uri;
        proxy_cache_purge $purge_method;
        # 當分配的服務器出現50X 錯誤時分配另外一臺服務器
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504
    }
}
複製代碼

5、Nginx深度學習

5.1 動靜分離

upstream java_api{
    server 127.0.0.1:8080;
}
server {
    ...
    #匹配到jsp結尾的請求去請求服務器
    location ~ \.jsp$ {
        proxy_pass http://java_api;
        index index.html index.htm;
    }
    
    #匹配到圖片資源返回本地的內容
    location ~ \.(jpg|png|gif)$ {
        expires 1h;
        gzip on;
    }
}
複製代碼

5.2 Nginx 的 rewrite規則

做用:實現 url 重寫以及重定向

使用場景:

  • URL 訪問跳轉,支持開發設計

    ​ 頁面跳轉、兼容性支持、展現效果等

  • SEO優化

  • 維護。後臺維護、流量轉發等

  • 安全

語法

Syntax:	rewrite regex replacement [flag];
Default:	—
Context:	server, location, if
複製代碼

If the specified regular expression matches a request URI, URI is changed as specified in the *replacement* string. The rewrite directives are executed sequentially in order of their appearance in the configuration file. It is possible to terminate further processing of the directives using flags. If a replacement string starts with 「http://」, 「https://」, or 「$scheme」, the processing stops and the redirect is returned to a client.

An optional *flag* parameter can be one of:

  • last

    中止rewrite檢測

    stops processing the current set of ngx_http_rewrite_module directives and starts a search for a new location matching the changed URI;

  • break

    中止rewrite檢測

    stops processing the current set of ngx_http_rewrite_module directives as with the break directive;

  • redirect

    返回302臨時重定向,地址欄會顯示跳轉後的地址

    returns a temporary redirect with the 302 code; used if a replacement string does not start with 「http://」, 「https://」, or 「$scheme」;

  • permanent

    返回302永久重定向,地址欄會顯示跳轉後的地址

    returns a permanent redirect with the 301 code.

The full redirect URL is formed according to the request scheme ($scheme) and theserver_name_in_redirect and port_in_redirect directives.

Example:

server {
    ...
    rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;
    rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra  last;
    return  403;
    ...
}
複製代碼

But if these directives are put inside the 「/download/」 location, the last flag should be replaced bybreak, or otherwise nginx will make 10 cycles and return the 500 error:

location /download/ {
    rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 break;
    rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra  break;
    return  403;
}
複製代碼

If a *replacement* string includes the new request arguments, the previous request arguments are appended after them. If this is undesired, putting a question mark at the end of a replacement string avoids having them appended, for example:

rewrite ^/users/(.*)$ /show?user=$1? last;
複製代碼

If a regular expression includes the 「}」 or 「;」 characters, the whole expressions should be enclosed in single or double quotes.

5.3 安全校驗 secure_link

指定並容許檢查請求的連接的真實性以及保護資源免遭未受權的訪問

限制連接生效週期

Syntax:	secure_link expression;
Default:	—
Context:	http, server, location

Syntax:	secure_link_md5 expression;
Default:	—
Context:	http, server, location
複製代碼

Example:

location /s/ {
    secure_link $arg_md5,$arg_expires;
    secure_link_md5 "$secure_link_expires$uri$remote_addr secret";

    if ($secure_link = "") {
        return 403;
    }

    if ($secure_link = "0") {
        return 410;
    }

    ...
}
複製代碼

5.3 geoip_module 模塊

基於 IP 地址匹配 MaxMind GeoIP 二進制文件,讀取 IP 所在地域信息

安裝: yum install nginx-module-geoip

使用場景

  • 區別國內外作HTTP 訪問規則
  • 區別國內城市地域作 HTTP 訪問規則

5.4 配置 HTTPS

server {
    listen              443 ssl;
    server_name         www.example.com;
    ssl_certificate     www.example.com.crt;
    ssl_certificate_key www.example.com.key;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    ...
}
複製代碼

HTTPS 服務優化

  • 激活 keepalive 長鏈接
  • 設置 ssl session 緩存
server{
    listen 		 443;
    server_name  116.62.103.228 jeson.t.imooc.io;
    keepalive_timeout  100;
    
    ssl on;
    ssl_session_cache  shared:SSL:10m;
    ssl_session_timeout  10m;
    
    ssl_certificate     www.example.com.crt;
    ssl_certificate_key www.example.com.key;
    
    index index.html index.htm;
    location / {
        root /opt/app/code;
    }
}
複製代碼

5.5 Nginx 與 Lua 開發

Lua 是一個簡潔、輕量、可擴展的腳本語言

Nginx + Lua 優點:充分的結合 Nginx 的併發處理 epoll 優點和 Lua 的輕量實現簡單的功能且高併發的場景。

安裝

yum install lua
複製代碼

運行 lua 有兩種方式:命令行和腳本

  • 命令行模式

    在命令行輸入 lua 開啓命令行交互模式
    複製代碼
  • 腳本模式

    編寫 test.lua 文件,執行 lua test.lua 運行

註釋

-- 行註釋
--[[
    塊註釋
--]]
複製代碼

6、Nginx 常見問題

多個 server_name 的優先級

若是多個文件配置有相同的 server_name ,根據文件名先讀取到哪一個文件就加載哪一個文件的配置

location 匹配優先級

=  進行普通字符精確匹配,也就是徹底匹配
^~ 表示普通字符匹配,使用前綴匹配
~ \~*  表示執行一個正則匹配()
複製代碼

前兩種匹配到以後就不往下繼續匹配了,最後一種會繼續往下匹配,若是沒有匹配到,就用它的匹配。也就是前兩種優先級比第三種高。

try_files 的使用

按順序檢查文件是否存在

location / {
    try_files $uri $uri/ /index.php;
}
複製代碼

7、Nginx 性能優化

7.1 文件句柄

文件句柄:linux\Unix 一切皆文件,文件句柄就是一個索引

設置方式:系統全局性修改,用戶局部性修改,進程局部性修改

修改方法:

系統全局修改和針對用戶修改

vim /etc/security/limits.conf
複製代碼

加入如下代碼

# 給root用戶設置
root soft nofile 10000
root hard nofile 10000
# 給全部用戶全局設置
*    soft nofile 10000
*    hard nofile 10000
複製代碼

soft 不是強制性的,超過設置的值會提醒但不強制執行;hard 會強制執行

針對進程修改

vim /etc/nginx/nginx.conf
複製代碼

添加如下代碼

worker_rlimit_nofile 20000
複製代碼

7.2 CPU 親和

查看當前服務器的 CPU 個數

cat /proc/cpuinfo | grep "physical id"|sort|uniq|wc -l
複製代碼

查看 CPU 核數

cat /proc/cpuinfo | grep "cpu cores"|uniq
複製代碼

worker_processes = CPU 個數 * CPU 核數

假若有 2 個 CPU,每一個 CPU 有 8 核,那 worker_processes 應該是16

打開 nginx 配置文件 vim /etc/nginx/nginx.conf

worker_processes  16;
worker_cpu_affinity  auto;
複製代碼

而後刷新nginx配置 nginx -s reload -c /etc/nginx/nginx.conf

7.3 Nginx 的通用配置

user  nginx;
worker_processes  1;
worker_cpu_affinity auto;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

worker_rlimit_nofile 10000;

events {
    use epoll;
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    charset utf-8;

    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  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush on;

    keepalive_timeout  65;

    gzip  on;
    gzip_disable  "MSIE [1-6]\.";
    gzip_http_version 1.1;

    include /etc/nginx/conf.d/*.conf;
}
複製代碼

8、基於 Nginx 架構的安全

8.1 常見的惡意行爲及防範手段

常見惡意行爲:爬蟲行爲和惡意抓取、資源盜用

經常使用防範手段:

基礎防盜鏈功能:目的不讓惡意用戶輕易爬取網站數據

secure_link_module: 提升數據安全性,對數據增長加密驗證和失效性,適合核心重要數據

access_module: 對後臺、部分用戶服務的數據提供 IP 防控

8.2 常見的攻擊手段

後臺密碼撞庫

經過猜想密碼字段不斷對後臺系統登陸性嘗試,獲取後臺登陸密碼

防範手段:

  • 後臺登陸密碼複雜度
  • access_module 對後臺提供 IP 防控
  • 預警機制

文件上傳漏洞

location ^~ /upload{
    root /opt/app/images;
    if($requst_filename ~*(.*)\.php){
        return 403;
    }
}
複製代碼

SQL 注入

利用未過濾/未審覈用戶輸入的攻擊方法,讓應用運行本不該該運行的 SQL 代碼

Nginx + Lua 防火牆實現:github.com/loveshell/n…

以上就是 Nginx 學習筆記的所有內容。


做者正在組織寫一個有趣的開源項目 coderiver,致力於打造全平臺型全棧精品開源項目。

coderiver 中文名 河碼,是一個爲程序員和設計師提供項目協做的平臺。不管你是前端、後端、移動端開發人員,或是設計師、產品經理,均可以在平臺上發佈項目,與志同道合的小夥伴一塊兒協做完成項目。

coderiver 河碼 相似程序員客棧,但主要目的是方便各細分領域人才之間技術交流,共同成長,多人協做完成項目。暫不涉及金錢交易。

計劃作成包含 pc端(Vue、React)、移動H5(Vue、React)、ReactNative混合開發、Android原生、微信小程序、Angular、Node、Flutter、java後端的全平臺型全棧項目,歡迎關注。

目前已經組建了幾十人的研發團隊,將致力於爲你們提供最優質的開源項目。

項目地址:github.com/cachecats/c…

您的鼓勵是我前行最大的動力,歡迎點贊,歡迎送小星星✨ ~

相關文章
相關標籤/搜索