請求都用域名
test.com
root
http://nginx.org/en/docs/http/ngx_http_core_module.html#root
語法
Syntax: root path;
Default:
root html;
Context: http, server, location, if in location
一般配置
location /i/ {
root /data/w3;
}
請求 /i/top.gif
是找到文件 data/w3/i/top.gif
。
root 實現的是url 拼接。
location /mainland/pgc/ {
root /tmp/pgc/pgc/;
}
請求 http://test.com/mainland/pgc/
實際目錄為 /tmp/pgc/pgc/mainland/pgc/index.html
alias
http://nginx.org/en/docs/http/ngx_http_core_module.html#alias
語法
Syntax: alias path;
Default: —
Context: location
一般配置
location /i/ {
alias /data/w3/images/;
}
請求 /i/top.gif
是找到文件 /data/w3/images/top.gif
。
注意: alias 末尾需要增加 /
增加正則
官網文檔
if alias is used inside a location defined with a regular expression then such regular expression should contain captures and alias should refer to these captures (0.7.40), for example:
location ~ ^/users/(.+\.(?:gif|jpe?g|png))$ {
alias /data/w3/images/$1;
}
注意點: 當我們使用了正則,然后使用 alias ,我們必須在 alias 中使用正則的變量,
實際測試
nginx 版本: 1.12.2
當 nginx location 正則
alias
和 try_files
, 存在排斥情況。
示例
訪問URL: /mainland/pgc/index.html
location ~ (/(zh-cn|zh-hk|en|mainland))?/pgc/(.*) {
alias /www/dev/mainland/pgc/$3;
try_files $uri /mainland/pgc/$3;
index index.html index.htm;
}
上面正則中 $1 和$2
都是 mainland, $3的值為 index.html
。
根據上面配置后, 訪問 /mainland/pgc/index.html
,報錯為
2021/08/30 16:38:32 [error] 18570#0: *1249587 rewrite or internal redirection cycle while internally redirecting to "/mainland/pgc/index.html", client: 10.210.20.112, server: usmart-dev.baidu.com, request: "GET /mainland/pgc/index.html HTTP/1.1", host: "usmart-dev.baidu.com"
當我去除掉 try_files
, 也就是如下配置時
location ~ (/(zh-cn|zh-hk|en|mainland))?/pgc/(.*) {
alias /www/dev/mainland/pgc/$3;
index index.html index.htm;
}
訪問 /mainland/pgc/index.html
,正常。
正則使用變量名
location ~ (?<product>/(zh-cn|zh-hk|en|mainland))?/pgc/(?<page>.*) {
alias /www/dev/mainland/pgc/$page;
index index.html index.htm;
}
try_files
http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files
語法
Syntax: try_files file ... uri;
try_files file ... =code;
Default: —
Context: server, location
按指定順序檢查文件是否存在,並使用第一個找到的文件進行請求處理。處理的基於上下文處理的。文件的路徑是file 根據前面的 root 和 alias 指令作為參數構建的。可以通過在名稱末尾,指定斜杠來檢查目錄是否存在, 例如 $uri/
, 如果沒有找到任何文件, URL 則進行到最后一個參數中指定的內部重定向。 最后一個參數可以是URL 也可以是一個 code.
URL:
location / {
try_files $uri $uri/index.html /test/index.html;
}
code:
location / {
try_files $uri $uri/index.html $uri.html =404;
}
Example in proxying Mongrel:
location / {
try_files /system/maintenance.html
$uri $uri/index.html $uri.html
@mongrel;
}
location @mongrel {
proxy_pass http://mongrel;
}
一般配置:
try_files $uri $uri/ /index.html;