nginx web server 配置

 

 

1、基于ip和端口的虚拟主机

server {
listen  192.168.56.101:80;

}

2、基于域名的虚拟机主机

 

server {
server_name  www.example.com;

}

 

3. server 上下文常用指令

 

3.1 root

由于定义 location uri 对应访问服务器上根路径

server {

location / {

root   /var/www/html;     

}

    

}

 

3.2 index

用于显示和明确定义当request uri 访问的是服务器上的目录时,服务器应该返回给客户端的页面。

例如:

server {

location  /index/ {

root   /var/www/html/;

index  home.html;

}

}

如上设定,服务器的响应情况如下:

1、当访问/index/ 时,服务器将显示 /var/www/html/index/目录下的home.html给客户端。如果没有明确指定index指令,将返回index.html,如果 /var/www/html/index/下没有index.html 将报错。

2、当访问/index/salt/时, 按照上面的虚拟机主机定义,nginx将在服务器的/var/www/html/index/ 下查找salt文件或者目录,如果salt是文件,则直接响应,如果是目录,则在salt目录下查找home.html的文件,如果没有则报错。

 

 3.3 location

location 支持2种类型的参数

  • prefix strings (pathnames) 
  • regular expressionsnginx first compares the URI to the locations with a prefix string. It then searches the locations with a regular expression

 

 

  1.  prefix strings 格式如下,location 指令后面指定具体路径名
    匹配以/some/path/ 开头的uri

    location /some/path/ { ... }
    精确匹配,uri 等于/some/path/ location
    = /some/path/ {    ... }

     

  2.  regular expressions格式如下:正则表达式以~开头的表示大写敏感;以~*开头表示大小写不敏感; ^~ 表示已特定字符串开头。

 

nginx location 匹配规则:

 

1.用uri测试所有的prefix string;
2.Uri精确匹配到=定义的loacation,使用这个location,停止搜索;
3.匹配最长prefix string,如果这个最长prefix string带有^~修饰符,使用这个location,停止搜索,否则:
4.存储这个最长匹配;
5.然后匹配正则表达;
6.匹配到第一条正则表达式,使用这个location,停止搜索;
7.没有匹配到正则表达式,使用#4步存储的prefix string的location。

 

 

 

 

3.3 返回特定状态码

格式:

location /wrong/url {
    return status_code optional_parameter;
}

 


return 指令第一个参数是响应状态码,第二个是可选参数,它可以是重定向后的url地址(仅针对301,302303, and 307这些状态码)或者是响应body的具体文本内容

return 指令可以在server,location 上下文中使用

3.4 默认主机配置

 

 

3.5  uri 重写

例如:

 location /users/ {
    rewrite  ^/users/(.*)$   /show?user=$1 break;
}

3.6 错误处理

posted @ 2017-07-26 12:44  andypengx  阅读(255)  评论(0编辑  收藏  举报