IT序号网

Nginx作为web服务器

qq123 2021年06月13日 程序员 299 0
配置文件

 
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 文件中增加 主机名与地址的对应关系;

评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!