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 文件中增長 主機名與地址的對應關係;
相關文章
相關標籤/搜索