nginx server配置和指令详解

Setting Up Virtual Servers


virtual server的配置是放在http模块中,例如:
http {
server {
# Server configuration
}
}
在http中,可以定义多个virtual server以满足需要
下面的配置表示监听本机的8000端口:
server {
listen 127.0.0.1:8080;
# The rest of server configuration
}
如果写明监听哪个端口,那么将使用标准端口tcp 80 或默认端口 tcp 8000

在server块中,可以通过server_name来配置server的多域名,域名可以通过以下方式:
1、完整的域名,如www.example.com
2、带*号开头的域名,如 *.example.com
3、带*号末尾的域名,如 mail.*
4、可匹配的正则表达式


Configuring Locations

下面的配置将匹配以 /some/path/开头的URIs,例如:/some/path/document.html
location /some/path/ {
...
}

正则表达式能通过 ~ 符号 和 ~* 这两个符号表示,分别指正则表达式区分大小写和不区分大小写,以下例子表示匹配URIs中包含.html 或者.htm 的访问路径:
location ~ \.html? {
...
}
nginx会匹配最准确的路径,会先匹配相对路径,如果不匹配,再跟正则表达式进行匹配

以下例子中,第一个路径/images/的文件目录是/data,第二个路径表明nginx作为代理的角色将会把请求转给后端www.example.com的机器上
server {
location /images/ {
root /data;
}

location / {
proxy_pass http://www.example.com;
}
}
如果这样配置,那么除了/image/开头的URIs,其他的URIs将会以代理的方式传到后端机器

root 指令
root指令能指定那个目录作为根目录用于文件的检索,这个指令能用于http,server,location这些块中
下面的例子指定了virtual server文件检索的根目录:
server {
root /www/data;

location / {
}

location /images/ {
}

location ~ \.(mp3|mp4) {
root /www/media;
}
}
当一个URI以/image/开头,那么将会在 /www/data/images/这个目录下进行检索;当URI以 .mp3或.mp4结尾时,nginx将会在/www/media目录下检索资源

当一个请求以 / 结尾时,nginx会尝试在该目录下找到该请求的索引文件(index file)。默认的索引文件为index.html。
例如 如果URI为/images/some/path/,那么nginx会尝试查找/www/data/images/some/path/index.html文件,如果这个文件不存在,那么将默认返回404。
可以通过 autoindex指令来配置nginx自动生成目录文件列表,而不是返回index.html
location /images/ {
autoindex on;
}

如果想让nginx查找更多指定类型的索引文件,可以通过Index指令指定,如:
location / {
index index.$geo.html index.htm index.html;
}

try_files 指令
try_files指令会在原请求不存在时,重定向到指定的URI,并返回结果。例如:
server {
root /www/data;

location /images/ {
try_files $uri /images/default.gif;
}
}
/www/data/images/index.html不存在时,将会返回/www/data/images/default.gif文件

另外一种情况是返回状态码:
location / {
try_files $uri $uri/ $uri.html =404;
}

猜你喜欢

转载自blog.csdn.net/weixin_42175570/article/details/83536394
今日推荐