http_try_files_module
http_try_files_module 模塊只提供了try_files這一個指令,該模塊對於我們使用反向代理的時候有很大的幫助,該模塊是默認編譯進nginx框架當中的,無法將其取消。
在搭建wordpress站點的時候可以使用到try_files指令。該指令用於反向代理達到場景非常有用,可以先去嘗試在nginx上直接獲取磁盤上的內容,如果沒有這個文件再反向代理到上游服務。
try_files兩種語法
Syntax:
try_files file ... uri; --放文件路徑的名稱,可以放多個。也就是說訪問請求的時候,會依次嘗試這些文件是否可以返回,只要有一個文件可以返回就立刻返回該文件內容。如果所有的文件都訪問不了就按照最後一個url訪問的結果返回給用戶
try_files file ... =code; --最後一個url也可以是一個code,用來指定返回的錯誤碼
Default: —
Context: server, location
功能:依次訪問多個url對應的文件(由root或者alias指令指定),當文件存在時直接返回文件內容,如果所有文件不存在,則按照最後一個URL結果或者code返回
舉幾個例子如下
(1)
Nginx的try_files作用:按選項所指定的順序去檢查用戶請求的文件是否存在,如果本地存在的話則返回該請求;不存在的話將該請求轉發到指定的其他路徑
location / {
try_files $uri @java_page;
}
location @java_page {
proxy_pass http://127.0.0.1:8080
}
(2)
server {
listen 80;
server_name api.xxx.com;
root /mnt/try;
location / {
add_header Content-Type 'text/html; charset=utf-8';
#echo $uri;
try_files $uri @default;
}
location @default {
root /mnt/default;
}
}
location @xxx解釋:定義一個location段,不能被外部請求所訪問,只能用於nginx內部配置指令使用,比如 try_files、error_page。
$uri解釋:URI代表資源的名稱,瀏覽器訪問 http://api.xxx.com/abc/index.html 時,當前的$uri值爲/abc/index.html
try_files作用:try_files會先嚐試去/mnt/try目錄下找abc目錄下的index.html,如果有,直接返回,沒有的話則跳轉到@default部分(內部重定向)。在default部分會去/mnt/default目錄下找abc目錄下的index.html,有,直接返回,沒有就返回404錯誤。try_files可以理解爲實現rewrite的作用。
(3)
server {
error_log logs/myerror.log info;
root html/;
default_type text/plain;
location /first {
try_files /system/maintenance.html #當訪問frist指令,會去看看是否存在maintenance.html 這樣一個文件。
如果這個文件找不到
$uri $uri/index.html $uri.html --如果這些資源都沒有會去訪問@lasturl
@lasturl;
}
location @lasturl {
return 200 'lasturl!\n';
}
location /second {
try_files $uri $uri/index.html $uri.html =404; --會嘗試訪問裏面所有的文件,當所有文件都找不到返回404
}
}
[root@www ~]# curl 192.168.179.99/first
lasturl!
[root@www ~]# curl 192.168.179.99/second
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.16.1</center>
</body>
</html>
(4)
location / {
root html/;
try_files $uri $uri/index.html $uri.html
@lasturl;
}
location @lasturl {
return 200 'lasturl!\n';
}
[root@www html]# curl 192.168.179.99 --如果可以訪問到資源,直接返回資源
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>