当前位置:  首页>> 技术小册>> Web服务器Nginx详解

一、默认网站

  1. server {
  2. listen 80;
  3. server_name localhost;
  4. location / {
  5. root html;
  6. index index.html index.htm;
  7. #支持目录浏览
  8. autoindex on;
  9. }
  10. error_page 500 502 503 504 /50x.html;
  11. location = /50x.html {
  12. root html;
  13. }
  14. }

二、访问控制

  1. location /a {
  2. autoindex on;
  3. allow 192.168.12.0/24;
  4. deny all;
  5. #基于客户端IP做过滤,符合条件的允许访问,不符合的返回404;
  6. if ( $remote_addr !~ "192.168.12" ) {
  7. #return 404;
  8. return http://book.ayitula.com;
  9. }
  10. }

三、登陆验证

  1. location /c {
  2. auth_basic "登陆验证";
  3. auth_basic_user_file /etc/nginx/htpasswd;
  4. }

四、日志管理

Nginx访问日志主要有两个参数控制

log_format #用来定义记录日志的格式(可以定义多种日志格式,取不同名字即可)

access_log #用来指定日至文件的路径及使用的何种日志格式记录日志

access_log logs/access.log main;

  1. log_format格式变量:
  2. $remote_addr #记录访问网站的客户端地址
  3. $remote_user #远程客户端用户名
  4. $time_local #记录访问时间与时区
  5. $request #用户的http请求起始行信息
  6. $status #http状态码,记录请求返回的状态码,例如:200、301、404等
  7. $body_bytes_sent #服务器发送给客户端的响应body字节数
  8. $http_referer #记录此次请求是从哪个连接访问过来的,可以根据该参数进行防盗链设置。
  9. $http_user_agent #记录客户端访问信息,例如:浏览器、手机客户端等
  10. $http_x_forwarded_for #当前端有代理服务器时,设置web节点记录客户端地址的配置,此参数生效的前提是代理服务器也要进行相关的x_forwarded_for设置

自定义一个json格式的访问日志

  1. log_format main_json '{"@timestamp":"$time_local",'
  2. '"client_ip": "$remote_addr",'
  3. '"request": "$request",'
  4. '"status": "$status",'
  5. '"bytes": "$body_bytes_sent",'
  6. '"x_forwarded": "$http_x_forwarded_for",'
  7. '"referer": "$http_referer"'
  8. '}';
  9. access_log logs/access_json.log main_json;

日志截断

  1. mv access.log access.log.0
  2. killall -USR1 \`cat master.nginx.pid\`
  3. sleep 1
  4. gzip access.log.0

五、防盗链

  1. location /images/ {
  2. alias /data/images/;
  3. valid_referers none blocked *.ayitula.com;
  4. if ($invalid_referer) {
  5. rewrite ^/
  6. http://www.ayitula.com/daolian.gif;
  7. #return 403;
  8. }
  9. }

该分类下的相关小册推荐: