一文讀懂 nginx配置

一、文件說明

html:放靜態文件
conf:配置文件
logs:日誌
sbin:nginx 啓動

二、命令

nginx  #啓動
nginx -s stop  / nginx -s quit #停止服務
nginx -t 檢查配置文件
nginx -s reload # 重啓 nginx
nginx -c /usr/local/nginx/conf/nginx.conf #啓動指定加載的配置文件

三、nginx.conf

user  nobody;       #主模塊命令, 指定Nginx的worker進程運行用戶以及用戶組,默認由nobody賬號運行。
worker_processes  1;     #指定Nginx要開啓的進程數。
#用來定義全局錯設日誌文件的路徑和日誌名稱。
#日誌輸出級別有debug,info,notice,warn,error,crit 可供選擇,其中debug輸出日誌最爲詳細,面crit(嚴重)輸出日誌最少。默認是error
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

pid        logs/nginx.pid;  #用來指定進程id的存儲文件位置。當解開這個命令時,查看 nginx.pid 文件即可查看 nginx 運行的 pid

#use 其中參數use用來指定nginx的工作模式(這裏是epoll,epoll是多路複用IO(I/O Multiplexing)中的一種方式),nginx支持的工作模式有select ,poll,kqueue,epoll,rtsig,/dev/poll。其中select和poll都是標準的工作模式,kqueue和epoll是高效的工作模式,對於linux系統,epoll是首選。

#event.worker_connection   是設置nginx每個進程最大的連接數,默認是1024,所以nginx最大的連接數max_client=worker_processes * worker_connections。進程最大連接數受到系統最大打開文件數的限制,需要設置ulimit。
events {
    worker_connections  1024;
}

http {
    include       mime.types;  #主模塊命令,對配置文件所包含文件的設定,減少主配置文件的複雜度,相當於把部分設置放在別的地方,然後在包含進來,保持主配置文件的簡潔
    default_type  application/octet-stream; #默認文件類型,當文件類型未定義時候就使用這類設置的。

    #指定nginx日誌的格式
    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路徑 這裏的 main 和log_format的 main 一致。
    #能access_log 使用 log_format的日誌格式
    access_log  logs/access.log  main;

    sendfile        on;#開啓高效文件傳輸模式(zero copy 方式),避免內核緩衝區數據和用戶緩衝區數據之間的拷貝。
    #tcp_nopush     on;#開啓TCP_NOPUSH套接字(sendfile開啓時有用)

    #客戶端連接超時時間
    keepalive_timeout  65;

    #設置是否開啓gzip模塊
    #gzip  on;

    server {
        #虛擬主機的服務端口
        listen       80;
        #用來指定ip或者域名,多個域名用逗號分開
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
         #地址匹配設置,支持正則匹配,也支持條件匹配,這裏是默認請求地址,用戶可以location命令對nginx進行動態和靜態網頁過濾處理
         
            #虛擬主機的網頁根目錄
            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;
        #    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;
        #}
    }


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

}

四、 http

1.log_format 的格式參數:

image

五、 server

本機配置:

/usr/local/nginx/conf/nginx.conf 在 http 內層,與server同級添加

include /usr/local/nginx/conf/extra_conf/*.conf;

在/usr/local/nginx/conf/extra_conf 中添加 **.conf 文件,內配置單個 server 配置項

server{
    listen       80;
    server_name  localhost;
    location .......
}

1.location匹配

image

匹配規則
~     波浪線表示執行一個正則匹配,區分大小寫
~*    表示執行一個正則匹配,不區分大小寫
^~    ^~表示普通字符匹配,如果該選項匹配,只匹配該選項,不匹配別的選項,一般用來匹配目錄
=      #進行普通字符精確匹配
1.精準匹配

訪問地址必須爲 url/a/。如果是 url/a 那麼這個不匹配

location =/a/ {
        rewrite ^/  /a.html break;
        root   html/static/;
}
2.一般匹配

訪問地址可爲
url/b/a
url/b/a/
url/b/a/任何值…

但是下面不可
url/任何值/b/a

location /b/a {
        rewrite ^/  /c.html break;
	root   html/static/;
}

訪問地址如果是直接訪問 html
html 文件路徑:html/static/a.html
瀏覽器路徑:http://127.0.0.1:8003/static/a.html

location /static {
		#root聲明,在html文件夾,查找/static/a.html文件

		root html/;
        }
3.正則匹配

訪問地址可爲:
url/b/c
url/b/c/
url/b/c/任何值…
url/任何值…/b/c/任何值…

location ~/b/c/* {
        rewrite ^/  /e.html break;
        root   html/static/;
}

地址會先匹配 一般匹配,如果一般匹配匹配上了,還會再走正則匹配。最終走正則匹配
如上面 那個location 與下面這個 location 並存,則下面這個會失效。

location /b/c/a {
	return 401;
}

url/b/d/a 訪問 f.html
url/b/d/a/ 訪問 g.html
url/b/d/a/ss 訪問 g.html

location ^~ /b/d/a/ {
        rewrite ^/  /g.html break;
        root   html/static/;
}
location ~ /b/d/* {
        rewrite ^/  /f.html break;
        root  /usr/local/nginx/html/static/;
}

注:… 代表中間可以多級目錄

2.nginx 指令

root

root 後的 test_html(默認是 html) 代表 nginx/html 文件夾

location / {
            root   test_html;
            index  index.html index.htm;
        }

alias

尋址時/test 就相當於test_html文件夾的別稱。如nginx 中有如下目錄:test_html/test_static/a.html。
那麼瀏覽器地址欄中輸入如下地址即可找到a.html:/test/test_static/a.html

  location /test {
            alias   test_html;
            index  index.html index.htm;
        }

proxy_pass

反向代理
如原服務地址爲:
http://127.0.0.1:9003/user/abc/bbc/select
nginx配置:
http://127.0.0.1:9003/user/abc/
最後瀏覽器訪問地址:
http://127.0.0.1:8002/test/bbc/select
注:反向代理地址 有無『/』都不影響。只會對upstream 分發地址的時候有影響

    location /test {
       proxy_pass   http://127.0.0.1:9003/user/abc/;
    }

如果是如下配置,那麼遵循下面 upstream 注2 的規則

    location /test {
       proxy_pass   http://127.0.0.1:9003;
    }

upstream

proxy_pass 後的 http://adminservice/; 對應upstream後的adminservice
注1:upstream 的被代理地址只能寫到端口,不可127.0.0.1:9003/xx 這樣,配置文件會不通過
注2:如果proxy_pass http://adminservice(不帶"/"),那麼最後拼接的地址會帶上 location 中的/test。 如:瀏覽器地址爲:http://127.0.0.1:8002/user/abc,那麼最後的地址會爲 127.0.0.1:9003/test/user/abc
如果 proxy_pass http://adminservice/(帶"/"),那麼最後的拼接地址就會不帶 location 的 /test。如:瀏覽器地址爲:http://127.0.0.1:8002/user/abc,那麼最後的地址會爲 127.0.0.1:9003/user/abc

因爲請求接口時,端口後的域名段不可能都一樣,所以實際中,proxy_pass必須帶『/』
負載均衡
1、輪詢(默認)
每個請求按時間順序逐一分配到不同的後端服務器,如果後端服務器down掉,能自動剔除。
2、weight
指定輪詢機率,weight和訪問比率成正比,用於後端服務器性能不均的情況。down 暫時不參與負載
3、ip_hash
每個請求按訪問ip的hash結果分配,這樣每個訪客固定訪問一個後端服務器,可以解決session的問題。

http{
    upstream adminservice {
                    server 127.0.0.1:9003 weight=2;
                    server 127.0.0.1:9002;
            }


    server {
            listen       8002;
            server_name  127.0.0.1;
    
            location /test {
               proxy_pass   http://adminservice/;
            }
    
        }
}

3.rewrite

image
格式:
rewrite regex replacement [flag]; flag=【break/last/redirect/permanent】
regex 是正則表達式
replacement 是替換值,新值
flag – 是處理標誌

簡單例子

瀏覽器 url:http://127.0.0.1:80/aa.html
最終訪問:html/a.html
正則:『^/』表示適配任何值。
location 匹配了aa.html 進入 location中。 rewrite 的正則匹配爲任何值。所以最終訪問的頁面是 a.html.root 指向 html 所以最終訪問的是 html/a.html

location /aa.html {
	rewrite ^/  a.html break;
	root  html;
}
rewrite沒有命中

瀏覽器 url:http://127.0.0.1:80/aa.html
最終訪問:html/aa.html
location 的匹配是 aa.html 的 url,而 rewrite 的匹配是 xx.js 的 url,所以 rewrite 會永遠匹配不上。相當於沒有 rewrite,所以最終訪問的是html/aa.html ,html 下沒有 aa.html 頁面就會返回404

location /aa.html {
	rewrite /*.js  a.html break;
	root  html;
}
flag

/redirect(狀態碼302)/permanent(狀態碼301)
如果rewrite命中,發頁面重定向,瀏覽器地址欄會變
瀏覽器初始地址欄:http://127.0.0.1:8004/bb
發送請求後地址欄:http://127.0.0.1:8004/b.html

location /bb {
    rewrite ^/  /b.html permanent;
	root   html/;
}

break/last 內部重定向,換path值
break標記,停止執行後續命令
瀏覽器 url:http://127.0.0.1:8004/aa.html
進入頁面:html/static/b.html
當進入到當前 location 中後,首先匹配到 b.html,然後執行 break。那麼後面 rewrite a.html 命令就不會再執行了。

location /aa.html {
	rewrite ^/  /b.html break;
	rewrite ^/  /a.html break;
	root   html/static/;
}

last標記,會引發location重新匹配
瀏覽器 url:http://127.0.0.1:8004/ab.html
最終結果:頁面報錯

當通過匹配進入到了 ab.html的 location 中,但是 rewrite 又重定向到了 a.html 而且使用 last 修飾,發生了 location 重新匹配。這就相當於瀏覽器的 url 是http://127.0.0.1:8004/a.html 。所以就又進入到了 a.html location 當中,之後又 last 到了 ab.html,所以就引發了死循環。而且使用 last,以後中斷他下面的語句。
ps:不要輕易使用last標籤

location /a.html {
	rewrite  ^/  /ab.html last;
}

location /ab.html {
        #rewrite ^/  /a.html last;
        root   html/static/;
}

4.nginx執行過程

image
說明:
1.通過域名、端口 進入對應的 server
2.path分爲兩部分:path1(匹配 location 部分)+path2
3.代理轉發:
      root:在目錄裏找path1+path2路徑
      alias:在目錄裏找path2路徑
            index:

        #root/alias,若頁面以 『/』結尾,則認爲 path 只到目錄,此時啓動 index,找目錄內 index 的文件
        server{
        	listen       8005;
            server_name  127.0.0.1;
            #文件存放位置 html/static/a.html、b.html
            
            #訪問 http://127.0.0.1:8005/static 會報301(使用 curl 命令查看)
            #訪問 http://127.0.0.1:8005/static/ 訪問到 a.html 頁面
        	location /static {
        		root html/;
        		index a.html;
                }
        
            #訪問 http://127.0.0.1:8005/target 會報301(使用 curl 命令查看)
            #訪問 http://127.0.0.1:8005/target/ 訪問到 b.html 頁面
        	location /target {
                alias html/static/;
                index b.html;
        	}	
        }

      proxy_pass:
          當後面跟的是 ip:端口
               有『/』:那麼就去對應服務器找 path2
               沒有『/』:那麼就去對應服務器找 path1+path2

location /test {
       #有 / 和沒有 /
       proxy_pass   http://127.0.0.1:9003/;
       proxy_pass   http://127.0.0.1:9003;
    }

          當後面跟的是 ip:端口/aa/bb…
               無論有沒有 『/』,都去找對應服務器的 path2

六、nginx 內置變量

image
image

image

七、跨域

CORS是一個W3C標準,全稱是"跨域資源共享"(Cross-origin resource sharing)。
它允許瀏覽器向跨源服務器,發出XMLHttpRequest請求,
從而克服AJAX只能同源使用的限制。
簡單請求:
瀏覽器在跨源AJAX請求的頭信息之中,自動在添加一個Origin字段(本次請求來自哪個源 )。
服務器根據這個值,在許可範圍內,則在頭信息包含 Access-Control-Allow-Origin 。
複雜請求:
會在正式通信之前,增加一次HTTP查詢請求,稱爲"預檢"請求OPTIONS

需要跨域的原因

image
1.瀏覽器向A 域名發起請求 請求到了 father 頁面,服務器將 html 頁面發給瀏覽器,顯示在瀏覽器當中
2.html 頁面 再次發起 ajax 請求,向 B 域名發起請求。返回數據後瀏覽器發現第一次請求是從 A 域名發起的,第二次請求是從 B 域名發起的。兩次請求域名不一樣,發生了跨域問題。瀏覽器機制不允許這樣的,所以會在 console 中報錯:
image
注:第二次請求實際已經發送出去了,但是返回結果瀏覽器是不允許加載的。

解決方法:

1.瀏覽器第一次發起請求:

http://static.mynginx.com/static/
頁面存在 nginx 位置:html/static/cors.html
本次請求 服務器 nginx 配置

server{
	listen       80;
        server_name  static.mynginx.com;

	location / {

		root html/static/;
		index cors.html;
        }

}

2.請求到的頁面

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
	<br />
	<h2>a頁面</h2>
	<br />
	<div id = "testcors"></div>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
//$("#testcors").text("Hello world!");
	$.ajax({  
		 url:"http://www.mynginx.com/static/",  
		 async :false,  
		 type:"GET",  
		 success:function(data){  
		 	console.log(data);
			 $("#testcors").html(data);  
			 }  
	 });
</script>

3.瀏覽器通過 ajax 發起第二次請求

http://www.mynginx.com/static/
頁面存在 nginx 位置:html/static/cors.html
本次請求服務器 nginx 配置
發生作用地方:add_header Access-Control-Allow-Origin $allow_url;把請求第一次請求的域名記錄註冊,允許此域名可跨域訪問。

server {
        listen       80;
        server_name  www.mynginx.com;
# nginx 校驗網址來源,符合那麼把$http_origin 賦值給 $allow_url 
	if ( $http_origin ~ http://(.*).mynginx.com){
                 set $allow_url $http_origin;
        }
  	 #是否允許請求帶有驗證信息
    	 add_header Access-Control-Allow-Credentials true;
    	 #允許跨域訪問的域名,可以是一個域的列表,也可以是通配符*
    	 add_header Access-Control-Allow-Origin  $allow_url;
    	 #允許腳本訪問的返回頭
    	 add_header Access-Control-Allow-Headers 'x-requested-with,content-type,Cache-Control,Pragma,Date,x-timestamp';
    	 #允許使用的請求方法,以逗號隔開
    	 add_header Access-Control-Allow-Methods 'POST,GET,OPTIONS,PUT,DELETE';
    	 #允許自定義的頭部,以逗號隔開,大小寫不敏感
    	 add_header Access-Control-Expose-Headers 'WWW-Authenticate,Server-Authorization';
    	 #P3P支持跨域cookie操作
    	 add_header P3P 'policyref="/w3c/p3p.xml", CP="NOI DSP PSAa OUR BUS IND ONL UNI COM NAV INT LOC"';
		 add_header test  1;

	 if ($request_method = 'OPTIONS') {
             return 204;
         }

	location /static {
			root   html/;
            index  a.html;
        }
        
    }

image

八、防盜鏈

瀏覽器地址:http://www.mynginx.com/untitled.html可加載出所有圖片
如果單獨訪問:http://www.mynginx.com/mall.jpg 顯示404

conf

# /mall* 的走這個
location ^~ /mall {
    # 驗證 網址
		valid_referers *.mynginx.com;
		    # 爲 true  返回404
    		if ($invalid_referer) {
    			return 404;
    		}
                root html;
        }

untitled.html

<html>
	<title>10:53:13 PM</title>
	<head></head>
	<body>
		<img src='http://www.mynginx.com/qq.png' />
		<img src='http://www.mynginx.com/chrome.png' />
		<img src='http://www.mynginx.com/mall.jpg' />
	</body>
</html>	

九、緩存

location ^~ /qq.png {
		expires 2s;#緩存2秒
	#	expires 2m;#緩存2分鐘
	#	expires 2h;#緩存2小時
	#	expires 2d;#緩存2天
		root html/gzip;
	}
	
location ^~ /chrome.png {
                expires 2m;#緩存2分鐘
                root html/gzip;
        }	

如下 qq.png 只緩存了2s,chrome.png 緩存了2分鐘,所以在多次刷新瀏覽器後,chrome.png 圖片
image

十、壓縮

配置如下即可

location ~ /(.*)\.(html|js|css|jpg|jpeg|png|gif)$ {#覆蓋/re/a.htm路徑
		gzip on; # 啓用gzip壓縮,默認是off,不啓用
		
		# 對js、css、jpg、png、gif格式的文件啓用gzip壓縮功能
		gzip_types application/javascript text/css image/jpeg image/png image/gif;
		gzip_min_length 1024; # 所壓縮文件的最小值,小於這個的不會壓縮
		gzip_buffers 4 1k; # 設置壓縮響應的緩衝塊的大小和個數,默認是內存一個頁的大小
		gzip_comp_level 1; # 壓縮水平,默認1。取值範圍1-9,取值越大壓縮比率越大,但越耗cpu時間
		
		root html/gzip;
	}

十一、https

生成密鑰:

# 1、創建服務器私鑰,命令會讓你輸入一個口令:
 openssl genrsa -des3 -out server.key 1024 
# 2、創建簽名請求的證書(CSR):
 openssl req -new -key server.key -out server.csr 
# 3、在加載SSL支持的Nginx並使用上述私鑰時除去必須的口令: 
openssl rsa -in server.key -out server_nopass.key 
# 4、最後標記證書使用上述私鑰和CSR:
 openssl x509 -req -days 365 -in server.csr -signkey server_nopass.key -out server.crt

conf

    server {
        listen       80;
        listen 443 ssl;
        server_name  localhost;
        //配置 https
        ssl_certificate /usr/local/mytest/server.crt;
        ssl_certificate_key /usr/local/mytest/server_nopass.key;
        ......

十二、 nginx 集羣

未學習

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章