Nginx部署和常见配置


目录:

  1. 安装Nginx

  2. Nginx配置解析

  3. 常见配置示例

    3.1 静态资源访问

    3.2 反向代理

    3.3 跨域

    3.4 负载均衡

    3.5 动静分离

    3.6 适配PC和移动端

    3.7 防盗链

    3.8 请求过滤

参考/来源:

安装Nginx

  • Windows

    可以参考这个

  • Mac

    通过homebrew安装,这里介绍

  1. 通过 brew info nginx 命令查看 Nginx 是否安装

    图片

    这里可以看到,显示未安装

  2. 通过 brew install nginx 命令安装 Nginx

    图片
    • 根目录是 /usr/local/var/www
    • 配置文件是 /usr/local/etc/nginx/nginx.conf
    • 默认端口是 8080
  3. Nginx常用命令

    nginx  启动
    nginx -s stop  停止
    nginx -s quit  安全退出
    nginx -s reload  重新加载配置文件
    ps aux|grep nginx  查看nginx进程

Nginx配置解析

  • 目录结构

    main        # 全局配置
    ├── events  # 配置网络连接
    ├── http    # 配置代理、缓存、日志等
    │   ├── upstream # 配置负载均衡
    │   ├── server   # 配置虚拟主机,可以有多个 server
    │   ├── server
    │   │   ├── location  # 用于匹配 URI(URL 是 URI 的一种),可以有多个 location
    │   │   ├── location
    │   │   └── ...
    │   └── ...
    └── ...
  • 默认配置文件/usr/local/etc/nginx/nginx.conf解析

    
    #user  nobody;
    worker_processes  1; # Nginx 进程数,一般设置为和 CPU 核数一样
    
    #error_log  logs/error.log;
    #error_log  logs/error.log  notice;
    #error_log  logs/error.log  info;
    
    #pid        logs/nginx.pid;
    
    # 配置网络连接
    events {
        worker_connections  1024; # 每个进程允许最大并发数
    }
    
    # 配置代理、缓存、日志等
    http {
        include       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  logs/access.log  main;
    
        sendfile        on; # 开启高效传输模式
        #tcp_nopush     on;
    
        #keepalive_timeout  0;
        keepalive_timeout  65; # 保持连接的时间,也叫超时时间,单位秒
    
        #gzip  on;
    
        # 配置负载均衡
        # upstream
    
        # 配置虚拟主机,可以有多个 server
        server {
            listen       8080; # 配置监听的端口
            server_name  localhost; # 配置的域名
    
            #charset koi8-r;
    
            #access_log  logs/host.access.log  main;
    	
    	      # 用于匹配 URI,可以有多个 location
            location / {
                root   html; # 网站根目录
                index  index.html index.htm; # 默认首页文件
                #deny 172.168.22.11;   # 禁止访问的ip地址,可以为all
        	      #allow 172.168.33.44; # 允许访问的ip地址,可以为all
            }
    
            #error_page  404              /404.html;
    
            # redirect server error pages to the static page /50x.html
            # 默认50x对应的访问页面
            error_page   500 502 503 504  /50x.html;
            location = /50x.html {
                root   html;
            }
    
            # proxy the PHP scripts to Apache listening on 127.0.0.1:80
            #
            #location ~ \.php$ {
            #    proxy_pass   http://127.0.0.1;
            #}
    
            # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
            #
            #location ~ \.php$ {
            #    root           html;
            #    fastcgi_pass   127.0.0.1:9000;
            #    fastcgi_index  index.php;
            #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
            #    include        fastcgi_params;
            #}
    
            # deny access to .htaccess files, if Apache's document root
            # concurs with nginx's one
            #
            #location ~ /\.ht {
            #    deny  all;
            #}
        }
    
    
        # another virtual host using mix of IP-, name-, and port-based configuration
        #
        #server {
        #    listen       8000;
        #    listen       somename:8080;
        #    server_name  somename  alias  another.alias;
    
        #    location / {
        #        root   html;
        #        index  index.html index.htm;
        #    }
        #}
    
    
        # HTTPS server
        #
        #server {
        #    listen       443 ssl;
        #    server_name  localhost;
    
        #    ssl_certificate      cert.pem;
        #    ssl_certificate_key  cert.key;
    
        #    ssl_session_cache    shared:SSL:1m;
        #    ssl_session_timeout  5m;
    
        #    ssl_ciphers  HIGH:!aNULL:!MD5;
        #    ssl_prefer_server_ciphers  on;
    
        #    location / {
        #        root   html;
        #        index  index.html index.htm;
        #    }
        #}
        # 加载子配置项
        include servers/*;
    }

常见配置示例

静态资源访问

参考上述默认配置文件即可。

还可以进行其他参数配置:

server {
  listen       80;
  server_name  static.sherlocked93.club;
  charset utf-8;    # 防止中文文件名乱码

  location /download {
    alias	          /usr/share/nginx/html/static;  # 静态资源目录
    
    autoindex               on;    # 开启静态资源列目录
    autoindex_exact_size    off;   # on(默认)显示文件的确切大小,单位是byte;off显示文件大概大小,单位KB、MB、GB
    autoindex_localtime     off;   # off(默认)时显示的文件时间为GMT时间;on显示的文件时间为服务器时间
  }
}

还可以设置缓存时间

# 图片缓存时间设置
location ~ .*\.(css|js|jpg|png|gif|swf|woff|woff2|eot|svg|ttf|otf|mp3|m4a|aac|txt)$ {
	expires 10d;
}

# 如果不希望缓存
expires -1;

反向代理

比如我们监听 9001 端口,然后把访问不同路径的请求进行反向代理:

  1. 把访问 http://127.0.0.1:9001/edu 的请求转发到 http://127.0.0.1:8080
  2. 把访问 http://127.0.0.1:9001/vod 的请求转发到 http://127.0.0.1:8081
server {
  listen 9001;
  server_name *.sherlocked93.club;

  location ~ /edu/ {
    proxy_pass http://127.0.0.1:8080;
  }
  
  location ~ /vod/ {
    proxy_pass http://127.0.0.1:8081;
  }
}

跨域

server {
  listen 9001;
  server_name fe.sherlocked93.club;

  location / {
    proxy_pass be.sherlocked93.club;
  }
}

负载均衡

http {
  upstream myserver {
  	# ip_hash;  # ip_hash 方式
    # fair;   # fair 方式
    server 127.0.0.1:8081;  # 负载均衡目的服务地址
    server 127.0.0.1:8080;
    server 127.0.0.1:8082 weight=10;  # weight 方式,不写默认为 1
  }
 
  server {
    location / {
    	proxy_pass http://myserver;
      proxy_connect_timeout 10;
    }
  }
}

动静分离

server {
  location /www/ {
  	root /data/;
    index index.html index.htm;
  }
  
  location /image/ {
  	root /data/;
    autoindex on;
  }
}

适配PC和移动端

server {
  listen 80;
	server_name fe.sherlocked93.club;

	location / {
		root  /usr/share/nginx/html/pc;
    if ($http_user_agent ~* '(Android|webOS|iPhone|iPod|BlackBerry)') {
      root /usr/share/nginx/html/mobile;
    }
		index index.html;
	}
}

防盗链

server {
  listen       80;        
  server_name  *.sherlocked93.club;
  
  # 图片防盗链
  location ~* \.(gif|jpg|jpeg|png|bmp|swf)$ {
    valid_referers none blocked server_names ~\.google\. ~\.baidu\. *.qq.com;  # 只允许本机 IP 外链引用,感谢 @木法传 的提醒,将百度和谷歌也加入白名单
    if ($invalid_referer){
      return 403;
    }
  }
}

请求过滤

# 非指定请求全返回 403
if ( $request_method !~ ^(GET|POST|HEAD)$ ) {
  return 403;
}

location / {
  # IP访问限制(只允许IP是 192.168.0.2 机器访问)
  allow 192.168.0.2;
  deny all;
  
  root   html;
  index  index.html index.htm;
}

文章作者: 小小千千
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小小千千 !
评论
  目录