※server
server {
listen 11111;
server_name localhost;
location / {
root xxx;
index one.html;
}
}
server {
listen 22222;
server_name localhost;
location / {
root /usr/local/nginx/xxx
#root D:\xxx
index two.html;
}
}
server {
listen 80;
server_name ooo.com
location / {
root xxx;
index name.html;
}
}
※改好可用 ./nginx -t 測試設定檔有沒有錯
※http 裡的 server 可以有很多
※可以有不同的 port
※root 可以寫絕對路徑和相對路徑
但絕對路徑可能會有權限問題
Linux 的相對路徑預設是 /usr/local/nginx;Windows 為 nginx.exe 同層
※server_name 的網址必需寫在 hosts 檔裡,Linux 在 /etc;Windows 在 %SystemRoot%\system32\drivers\etc
※log
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
log_format xxx $remote_addr
sendfile on;
server {
listen 11111;
server_name localhost;
location / {
root one;
index one.html;
}
access_log logs/access_11111.log main;
}
server {
listen 22222;
server_name localhost;
location / {
root D:;
index two.html;
}
access_log logs/access_22222.log xxx;
}
}
※每一個 server 裡都可以有一個自己的 log,log_format 後面定義一個名字,然後格式是 $開頭的東西,想知道更多可參考官網,使用瀏覽器或 curl 指令請求後,就可以看到 log 寫出來了
※locatioon
.官網.如果操作過程出現錯誤,請看 logs/error.log
.預設的 location 全部刪除,用 curl 指令或網址輸入 localhost 還是能抓到 html/index.html
.root 不寫,預設為 html,也就是 /usr/local/nginx/html,官網
.index 預設為 index.html,可以寫多個,用空隔隔開,找到第一個就用,找不到才往後找;但如果寫在 location 後面,只能寫一個,官網
.如果 location / 後面接檔案,index 的設定沒有效果,但不會報錯
.如果 location / 後面接目錄,index 的設定沒有效果,執行時會報 301 Moved Permanently
= ~ ~* ^~
=精準匹配
^~只匹配開頭
~正則匹配,大小寫不一樣
~*正則匹配,大小寫一樣
不加為一般匹配
※優先級
以完全相同為例精準匹配 > 開頭匹配 > 正則匹配 > 一般匹配
開頭匹配和一般匹配不能同時寫,啟動伺服器時會報錯
正則匹配有兩個,誰寫前面就抓誰
※
#location /one.txt {
# root one;
#}
location ~* /one.txt {
root regex_not_i;
}
location ~ /one.txt {
root regex_have_i;
}
location ^~ /one.txt {
root headXXX;
}
※
※匹配目錄
location = / {
root /usr;
index index.html;
}
location / {
root one;
index one.txt;
}
#location /index.html {
# root two;
# index two.txt;
#}
※如果只有一個精準的 location = /,那 curl localhost 會將精準匹配的 /加上 index.html,然後再次發出 /index.html;如果只有一個一般的 location /,那就會直接將檔案顯示出來或 404
※此例使用 curl localhost 會匹配到精準匹配的 /,一定要有 /usr/index.html (檔案或資料夾都可以),不然會 403 Forbidden
然後再次匹配 /index.html ,最適合的只有一般匹配的 /,所以會找 /usr/local/nginx/one/index.html (因為 location 和 index 都有檔案,會忽略 index 的 one.txt)
但如果連第二個也註解,那會去找預設的 /usr/local/nginx/html/index.html
※如果將最後一個 location 註解打開,那 /index.html 會匹配到註解的 location,此時會找 /usr/local/nginx/two/index.html
※如果想執行的是第一個 location 裡的檔案,要寫成 = /index.html 才可以,而 index 可以不寫,因為 location 和 index 都寫,index 會被忽略
沒有留言:
張貼留言