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 https://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;
- }
来源: https://www.2cto.com/kf/201810/784179.html