http服務器(動靜分離)
Nginx作為http服務器,可以用於存放靜態資源(比如css、圖片、音頻等),實現web服務的動靜分離。(tomcat等作為動態資源服務器。靜態資源訪問Nginx,其它訪問tomcat)。
配置流程
-
從原項目包種移除static靜態資源包的文件;
-
在/usr/nginx目錄下創建resources文件夾
-
將靜態資源包放入resources中
-
修改配置文件nginx.conf
location ~*\.(css|js|html)$ { root resources; #指向靜態資源 index index.html #配置緩存有效天數 expires 7d; } location ~\*.(jpg|png|mp3|mp4)$ { root resources; index index.html #有效天數 expires 20d; }
location基本語法:
location[ = | ~ | ~* | ^~] url{ }
-
= 精確匹配
-
~ 區分大小寫的正則匹配
-
~* 不區分大小寫的正則匹配
-
^~ 以某個常規字符串開頭的匹配
-
如果有url包含正則錶達式,不需要有~開頭標識
補充概念:
-
動靜分離:就是將css、js、jpg、音頻等靜態資源和jsp等動態資源分開處理,以提高服務器響應速度,提高性能。
rewrite/地址重定向
能够使用rewrite指令的字段包括:http、server、location。
Rewrite語法
rewrite 正則錶達式 定向後的比特置 [模式]
例子:
location /ecshop { index index.php; rewrite goods-([\d]+)\.html$ /ecshop/goods.php?id=$1; rewrite category-(\d+)-b(\d+)\.html /ecshop/category.php?id=$1&brand=$2 permanent; }
server { listen 80; server_name abc.com www.abc.com; if ( $host != 'www.abc.com' ) { rewrite ^/(.*) http://www.abc.com/$1 permanent; } location / { root /data/www/www; index index.html index.htm; } }
注意:用url重寫時, 正則裏如果有”{}”,正則要用雙引號包起來。
模式:
last
|
本條規則匹配完成後繼續向下匹配新的location URI規則
|
break
|
本條規則匹配完成後終止,不在匹配任何規則
|
redirect
|
返回302臨時重定向
|
permanent
|
返回301永久重定向
|
重寫中用到的指令:
- if (條件) {} 設定條件,再進行重寫
語法格式 if 空格 (條件) { 重寫模式 } 1: “=”來判斷相等, 用於字符串比較 2: “~” 用正則來匹配(此處的正則區分大小寫) ~* 不區分大小寫的正則 3: -f -d -e來判斷是否為文件,為目錄,是否存在. 例子:if (!-e $document_root$fastcgi_script_name) { #注: 此處還要加break rewrite ^.*$ /404.html break; }
- set #設置變量
if ($http_user_agent ~* msie) { set $isie 1; } if ($fastcgi_script_name = ie.html) { set $isie 0; } if ($isie = 1) { rewrite ^.*$ ie.html; }
- return #返回狀態碼
if ($remote_addr = 192.168.1.100) { return 403; }
- break #跳出rewrite
if ($http_user_agent ~ MSIE) { rewrite ^.*$ /ie.htm; #不break會循環重定向 break; }