色破飞机 发表于 2018-11-16 10:19:40

神奇的Nginx之常用设置

引言
  nginx软件十分小巧,较其竞争对手Apache而言,nginx可以实现的功能更为丰富,配置更为简单。Nginx采用多线程方式,对服务器内存大小要求不像apache那些高,此外其处理静态网页的速率、并发的访问量方面等都要比apache出色的多。目前越来越多的国内公司都开始使用nginx来代替apache搭建网站架构。本文介绍了部分常用nginx配置(核心代码)。

默认虚拟主机
  nginx可以实现配置文件的模块化分离,每个配置文件都是一个独立的虚拟主机。
  

# vim /usr/local/nginx/conf/vhost/test.com.conf  
server
  
{
  # 将该虚拟主机设置为默认虚拟主机
  listen 80 default_server;
  # 设置服务器的名称
  server_name default.com;
  # 设置服务器默认网页
  index index.html index.htm index.php;
  # 设置服务器的根目录
  root /data/www/default;
  
}
  

用户认证


[*]核心代码
  

    # 对目录  location /admin
  {
  auth_basic "User Auth";
  auth_basic_user_file /usr/local/nginx/conf/htpasswd;
  }
  # 对文件,可以直接写文件名,也可以是正则表示
  # ~ 匹配,~*模糊匹配(忽略大小写)
  location ~ .*\.php$
  {
  auth_basic "User Auth";
  auth_basic_user_file /usr/local/nginx/conf/htpasswd;
  }
  

域名重定向
  实现老站点向新站点域名的重定向
  

server  
{
  listen 80;
  # nginx可以配置多个主机名,apache只能使用ServerAlias来指定别名
  # nginx中哪个主机名在前,就是默认使用的主机名
  server_name test.com test2.com;
  index index.html index.htm index.php;
  root /data/www/test.com;
  # 判断host是否为test.com
  # permanent及返回状态码301,永久重定向
  if ($host != 'test.com') {
  rewrite ^/(.*)$ http://test.com/$1 permanent;
  }
  
}
  

访问日志
  

# 在nginx主配置文件nginx.conf内添加一下代码即可  
log_format test '$remote_addr $http_x_forwarded_for [$time_local]'
  ' $host "$request_uri" $status'
  ' "$http_referer" "$http_user_agent"';
  

  
# 设置好日志格式后,在虚拟主机内的server块内使用
  
access_log /tmp/test.com.log test;
  

  
# 如果某些情况下不需要记录日志,代码如下
  
access_log off;
  

静态文件不记录访问日志
  对于nginx静态文件访问日志不记录设置而言十分简单,其核心代码即expires time;
  

# 对不同的文件设置不同的过期时间  
# 过期时间单位可以是m/h/d等
  
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
  {
  expires 7d;
  }
  
location ~ .*\.(css|js)$
  {
  expires 12h;
  }
  

防盗链
  

location ~* .*\.(gif|jpg|png|swf|flv|rar|zip|doc|pdf|gz|bz2|jpeg|bmp|xls)$  {
  # 白名单可以是多个域名,域名间使用空格间隔开
  valid_referers none blocked server_names *.test.com;
  # 条件判断,非白名单域名返回403状态码即禁止访问forbidden;
  if ($invalid_referer) {
  return 403;
  }
  }
  

访问控制
  

# 对于目录  
location /admin/
  
{
  # nginx中没有apache里的order命令,按代码先后顺序执行
  # nginx中只要有一条规则匹配,后续规则就不会进行匹配
  # 允许本机
  allow 127.0.0.1;
  allow 192.168.65.133;
  # 禁止其他所有ip
  deny all;
  
}
  
# 针对文件
  
location ~ .*(upload|admin)/.*\.php$
  
{
  deny all;
  
}
  
# 针对user_agent
  
location /
  
{
  if ($http_user_agent ~ 'Spider/3.0|YoudaoBot|Tomato')
  {
  return 403; //等价于deny all;
  }
  
}
  

php文件解析
  

location ~ \.php$  {
  include fastcgi_params;
  # fastcgi_pass参数可以使用ip、sock
  # fastcgi_pass 127.0.0.1:9000;
  fastcgi_pass unix:/tmp/php-fcgi.sock;
  fastcgi_index index.php;
  fastcgi_param SCRIPT_FILENAME /data/www/test.com$fastcgi_script_name;
  }
  

  nginx还可以实现更多更有用的功能,这些知识点不是短短一篇博客就可以将去清楚的,本文基本上时nginx服务器基本功能实现的简单代码配置,日常生活工作中还是需要根据具体的需求还进行配置。


页: [1]
查看完整版本: 神奇的Nginx之常用设置