# Nginx靜態資源的配置指令 # listen指令 # 語法 listen address[:port][default_server] # 如: listen 127.0.0.1:8000; # 監聽指定ip和端口 listen 127.0.0.1:8000 default_server; # 監聽指定ip和端口,並設置為默認連接。默認連接就是在服務列表中沒有找到服務的時候默認訪問該服務 listen 127.0.0.1; # 監聽指定ip下的所有端口 listen 8000; # 監聽指定端口下的連接 listen *:8000; # 也是監聽指定端口下的連接 # 補充知識點:/etc/hosts域名解析文件配置 # ,當本地瀏覽器訪問某個域名的時候,首先會從/etc/hosts文件中查找,找不到再去dns中去找 # 所以你可以直接配置本地的域名 vim /etc/hosts 127.0.0.1 www.baidu.com # server_name指令 # 語法 server_name name1 name2 name3 …… # name的值可以是一個ip地址,也可以是域名,多個name之間需要用空格隔開 # 位置:只能在server中配置server_name # 如: server_name www.abc.cn www.a.cn # server_name的配置方式有三種 # 1.精准配置 server_name www.abc.cn www.a.cn # 2.通配符配置,通配符不能放在中部位置的,只能放在首尾位置 server_name *.abc.cn www.a.* # 3.正則表達式配置 # 以正則配置server_name的時候必須以~開頭 # 不明白正則怎么用的可以在該網站學習:https://www.runoob.com/regexp/regexp-syntax.html # 這里的(\w+)小括號的內容你可以在下文通過$1的方式獲取它的值 # 比如:輸入的是www.abc123.com,那么$1的值就是abc123,你可以在日志中引用 # 如果有多個()按順序$1 $2 $3 …… server_name ~^www.\.(\w+)\.com; # server_name 的匹配執行順序 # 也就是當一個一個請求能匹配多個server_name的時候,到底執行哪個server_name # 優先是精准匹配 # 然后是通配符在開頭的server_name # 再然后是通配符再結尾的server_name # 最后是正則表達式的server_name # 都沒找到的話就返回defualt_server 也就是not found server。 # location指令 # 語法:localtion [= 、 ~ 、 ~* 、 ^~ 、 @] uri{...} location /abc{ default_type text/plain; return 200 'access success'; } # =等號是精准匹配, # www.abc.com/abc 和 www.abc.com/abc?a=123 都可以訪問 # www.abc.com/abc/ 和 www.abc.com/abcd 都不能訪問 location =/abc{ default_type text/plain; return 200 'access success'; } # ~和~*表示當前uri包含了正則表達式,它們之間的區別是~區分大小寫,~*不區分大小寫 # 能匹配 www.abc.com/abc1 www.abc.com/abcdef # 不能匹配www.abc.com/abc location ~*^/abc\w${ default_type text/plain; return 200 'access success'; } # ^~,注意它是不包含正則表達式的前面,功能和不加符號的一直,唯一不同的是,如果模式匹配,那么就停止搜索其他模式了。 # location的搜索模式是一直往后搜索,然后取最后一個匹配的location # ^~的存在就是,搜索到該location並且匹配成功,就直接停止向后搜索 location ^~/abc{ default_type text/plain; return 200 'access success'; } # root、alias都是設置請求資源的目錄 # root語法:root path; # 默認值:html # alias語法:alias path; # 默認值:無 # 當訪問 localhost/images/mv.png時 # root情況下訪問的文件路勁是 html/images/mv.png # alias情況下范文的文件路徑是 html/mv.png # 得出結論是: # root處理結果是:root路徑+location路徑 # alias處理結果是: alias路徑替換location路徑 location /images { root html; } location /images { alias html; } # index指令 配置訪問目錄下默認訪問的文件。可以配置多個文件,空格隔開 # 它會從左往右依次去找,直到找到文件為止 # 語法:index file ...; index index.html index.hml # error_page 指令,用來設置網站的錯誤頁面 # 語法:error_page code ... [=[response]] uri # code是返回狀態碼 # 位置 http、server、location # 可以直接指定具體跳轉的地址 server { error_page 404 http://www.itcast.cn } # 可以指定重定向地址 server { error_page 404 50.html; error_page 500 502 503 504 /50x.html; location =/50x.html{ root html; } } # @語法 server { error_page 404 @jump_to_error; error_page 500 502 503 504 /50x.html; location @jump_to_error{ root html; } } # 可選項 =[response]的作用的是,將響應碼重新修改 # 也就是location中return的響應碼 # 這里本應該返回404響應碼,當加上=200的時候它就返回200了,而不反悔404 server { error_page 404 =200 @jump_to_error; error_page 500 502 503 504 /50x.html; location @jump_to_error{ root html; } }