Nginx做为web服务器

配置文件

 
Nginx的配置有着几个不一样段的上下文:
  • main
    • 对任何功能都生效的配置
    • 通常字段可省略
  • http
    • server
      • 必须属于http
      • 能够包含location
      • 每一个server表明一个虚拟主机
      • 不能够嵌套
    • upstream
      • 指定反向代理的
    • location
      • 其他子段
      • 能够在server中也能够在http中
      • 能够嵌套
  • Nginx能够有不少配置文件
配置语法的格式和定义方式遵循所谓的C风格,
所以支持嵌套,还有着逻辑清晰并易于建立、阅读和维护等优点。
 
  location
  • 语法
    • location [ = | ~ | ~* | ^~ ]  uri { ... }
  • location URI {}:
    • 对当前路径及子路径下的全部对象都生效;
  • location = URI {}:
    • 精确匹配指定的路径,不包括子路径,所以,只对当前资源生效;
  • location ~ URI {}:
    • ~区分字符大小写
    • 模式匹配URI,此处的URI可以使用正则表达式
  • location ~* URI {}:
    • 模式匹配URI,此处的URI可以使用正则表达式
    • ~*不区分字符大小写;
  • location ^~ URI {}:
    • 不使用正则表达式
  • 优先级:
    • "=" || "^~" || "~*" || “其他其余”
  • 访问控制
    • 基于ip地址访问控制
      • deny allow
        • 定义访问控制
        • 默认是容许访问的
        • 要拒绝全部指定给特定用户访问
          • allow IP
          • deny all
    • 基于用户访问控制
      • auth_basic  "访问限制"
      • auth_basic_user_file  "基于用户的认证"
        • htpasswd          管理用户帐户 生成文件。
          • 第二次不能使用-c选项;
实例

 
user  nginx;
worker_processes  2;
 
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
 
 
events {
    worker_connections  1024;
}
 
 
http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;
 
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
 
    access_log  /var/log/nginx/access.log  main;
 
    sendfile        on;
    tcp_nopush     on;
 
    keepalive_timeout  60;
 
    gzip  on;
 
   server {
     server_name a.ttlsa.com;
     listen 80;
     location / {
           root    /web/a.org;
           index  index.html;
     }
     location /bbs {
           root    /web;
           index  bbs.html;
     }
}
 
 
    include /etc/nginx/conf.d/*.conf;
}

  

 
 
注意:
访问www.a.org/bbs
其实是去  /web/bbs 去拿bbs.html;
所以 location的 中URI 既是 URI 又起到 目录做用;
 
基于主机名的虚拟主机

 
server {
     listen 80;
     server_name www.a.org;
     location / {
           root    /web/a.org;
           index  index.html;
     }
}
 

 

测试配置文件语法
  • nginx -t 
  • service nginx configtest
 
 
注意:须要在/etc/hosts 文件中增长 主机名与地址的对应关系;
相关文章
相关标签/搜索