Nginx官网: https://nginx.org/en/download.html

windows安装:

下载后解压(切记不能含有中文路径!!),文件结构如图(我解压的路径就有中文,记得拷贝放置于英文目录下即可!):

├── conf
├── contrib
├── docs
├── html
├── logs
├── temp
└──nginx.exe

启动的两种方式:

1) 直接双击该目录下的"nginx.exe",即可启动nginx服务器;

2) 命令行进入该文件夹,执行start nginx命令,也会直接启动nginx服务器。

启动服务:
start nginx
退出服务:
nginx -s quit
强制关闭服务:
nginx -s stop
重载服务:
nginx -s reload  (重载服务配置文件,类似于重启,服务不会中止)
验证配置文件:
nginx -t
使用配置文件:
nginx -c "配置文件路径"
使用帮助:
nginx -h

Linux安装:

Nginx依赖包

模块依赖性Nginx需要依赖下面3个包

ssl功能需要 openssl 库 ( https://www.openssl.org/ )

gzip模块需要 zlib 库 ( http://www.zlib.net/ )

rewrite模块需要 pcre 库 ( https://sourceforge.net/projects/pcre/ )

依赖包安装顺序依次为:openssl、zlib、pcre, 最后安装Nginx包。

nginx安装需要gcc环境

#直接安装gcc  pcre openssl等一系列环境
yum install -y gcc gcc-c++ pcre-devel openssl-devel wget

下载nginx源码

网址:nginx: download

命令:wget http://nginx.org/download/nginx-1.24.0.tar.gz

添加模块,新版本nginx会附带ssl,gzip,stream等模块,如果需要其他模块可以参考如下安装

解压nginx,并进入nginx解压目录,新建bundle目录

$ tar -zxvf nginx-1.10.1.tar.gz
 cd nginx-1.10.1$ mkdir bundle

解压pcre,并将解压后的整个目录复制到nginx-1.10.1/bundle目录下

$ tar -zxvf pcre-8.38.tar.gz
$ mv pcre-8.38 nginx-1.10.1/bundle/

解压openssl,并将解压后的整个目录复制到nginx-1.10.1/bundle目录下

$ tar -zxvf openssl-1.0.2h.tar.gz
$ mv openssl-1.0.2h nginx-1.10.1/bundle/

nginx添加模块命令

  • 系统中pcreopenssl都没有安装的情况

$ cd nginx-1.10.1$ sudo ./configure --prefix=/usr/local/nginx/ --with-openssl=bundle/openssl-1.0.2h 
   --with-pcre=bundle/pcre-8.38 --with-cc-opt="-Wno-deprecated-declarations"
  • 系统中安装了pcreopenssl的情况

$ cd nginx-1.20.1
$ sudo ./configure --user=nobody --group=nobody --prefix=/usr/local/nginx/ 
     --with-http_stub_status_module --with-http_gzip_static_module --with-http_realip_module 
     --with-http_sub_module --with-stream --with-http_ssl_module

项目

说明

--prefix=/usr/local/nginx/

nginx安装成功后所在目录

--with-openssl=bundle/openssl-1.0.2h

nginx依赖的openssl库源文件目录

--with-http_ssl_module

nginx依赖的openssl模块,如果系统中已经安装了openssl

那么将此选项替换上面的选项

--with-pcre=bundle/pcre-8.38

nginx依赖的pcre库源文件目录

--with-ld-opt="-L /usr/local/pcre-8.36/lib"

指定nginx依赖的pcre库所在目录

--with-cc-opt="-Wno-deprecated-declarations"

忽略错误

nginx1.24.0中示例:

./configure --prefix=/usr/local/nginx/ --with-http_realip_module --with-http_sub_module 
  --with-http_gzip_static_module --with-http_stub_status_module --with-http_ssl_module 
  --with-http_v2_module --with-stream --add-module=./module/ngx_http_geoip2_module-3.4

make并安装

$ cd nginx-1.20.1
$ sudo make install
或者
make PREFIX=/usr/local/nginx  install
# prefix=为想要安装的路径
#查看nginx在哪
>whereis nginx

创建软连接

> ln -sv /usr/local/nginx/sbin/nginx /usr/bin/nginx
‘/usr/bin/nginx’ -> ‘/usr/local/nginx/sbin/nginx’

验证文件及配置文件

> nginx -t
nginx: the configuration file /usr/local/nginx//conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx//conf/nginx.conf test is successful

mac环境安装

mac放开tcp连接数限制

ulimit -S -n 1048576 #默认256
sudo launchctl limit maxfiles 1048576 1048600  #默认256

环境依赖

需要git环境, 从官网下载: https://git-scm.com/downloads

需要homeBrew环境, 终端执行命令并设置下载源:

/bin/zsh -c "$(curl -fsSL https://gitee.com/cunkai/HomebrewCN/raw/master/Homebrew.sh)"

检查brew版本

brew update    // 更新brew

查询nginx是否存在

brew search nginx
brew info nginx

开始安装,

brew install nginx

ngix配置信息

nginx.conf配置文件路径: /usr/local/etc/nginx/

nginx程序所在: /usr/local/Cellar/nginx

静态网站目录: /usr/local/var/www

nginx命令

注意nginx.conf中 开启use root;  具体可读文件在哪个用户目录,就use哪个用户.

查看nginx运行程序

ps -ef | grep nginx
正常停止:kill -QUIT 主进程号
强制停止:kill -9 主进程号

版本查看 

nginx -v

版本查看及配置文件

nginx -V

启动命令:

nginx

启动并指定一个配置文件

nginx -c filename 为nginx指定一个配置文件

立即停止命令

nginx -s stop

平稳退出命令:

nginx -s quit

重新加载配置文件命令:

nginx -s reload

检查配置文件正确性:

nginx -t

nginx过滤国外IP

看 firewalld屏蔽国家IP文章

内置变量

nginx的配置文件中可以使用的内置变量以美元符$开始。其中,大部分预定义的变量的值由客户端发送携带。

  • $args :#这个变量等于请求行中的参数,同$query_string

  • $content_length :请求头中的Content-length字段。

  • $content_type :请求头中的Content-Type字段。

  • $document_root :当前请求在root指令中指定的值。

  • $host :请求行的主机名,为空则为请求头字段 Host 中的主机名,再为空则与请求匹配的server_name

  • $http_user_agent :客户端agent信息

  • $http_cookie :客户端cookie信息

  • $limit_rate :这个变量可以限制连接速率。

  • $request_method :客户端请求的动作,通常为GET或POST。

  • $remote_addr :客户端的IP地址。

  • $remote_port :客户端的端口。

  • $remote_user :已经经过Auth Basic Module验证的用户名。

  • $request_filename :当前请求的文件路径,由root或alias指令与URI请求生成。

  • $scheme :HTTP方法(如http,https)。

  • $server_protocol :请求使用的协议,通常是HTTP/1.0或HTTP/1.1。

  • $server_addr :服务器地址,在完成一次系统调用后可以确定这个值。

  • $server_name :服务器名称。

  • $server_port :请求到达服务器的端口号。

  • $request_uri :包含请求参数的原始URI,不包含主机名,如:”/foo/bar.php?arg=baz”。

  • $uri :不带请求参数的当前URI,$uri不包含主机名,如”/foo/bar.html”。

  • $document_uri :与$uri相同

日志格式

参数

说明

示例

$remote_addr

客户端地址

211.28.65.253

$remote_user

客户端用户名称

--

$time_local

访问时间和时区

18/Jul/2012:17:00:01 +0800

$request

请求的URI和HTTP协议

"GET /article-10000.html HTTP/1.1"

$http_host

请求地址,即浏览器中你输入的地址(IP或域名)

www.wang.com 192.168.100.100

$status

HTTP请求状态

200

$upstream_status

upstream状态

200

$body_bytes_sent

发送给客户端文件内容大小

1547

$http_referer

url跳转来源

https://www.baidu.com/

$http_user_agent

用户终端浏览器等信息

"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SV1; GTB7.0; .NET4.0C;

$ssl_protocol

SSL协议版本

TLSv1

$ssl_cipher

交换数据中的算法

RC4-SHA

$upstream_addr

后台upstream的地址,即真正提供服务的主机地址

10.10.10.100:80

$request_time

整个请求的总时间

0.205

$upstream_response_time

请求过程中,upstream响应时间

0.002

注意安全防护

配置Nginx账号锁定策略. 

不要以root启动, 修改nginx.conf中use nobody; 改为use liych;

#linux命令
passwd -l <nginx启动用户>  来锁定用户的密码. 

passwd -S userName, 查看用户状态 , 

passwd -U nginx  解锁用户密码
Nginx后端服务指定的Header隐藏状态

打开conf/nginx.conf配置文件(或主配置文件中的inlude文件);

http下增加或修改为

proxy_hide_header X-Powered-By;

proxy_hide_header Server;

隐藏Nginx服务的Banner, 版本号信息

打开conf/nginx.conf配置文件;

在server栏目下,配置 server_tokens off;

icoding.fit配置静态网站案例

#nginx.conf 请求和连接限流,geoIP过滤国外IP,Gzip压缩,cache缓存

user  userName;
worker_processes  1;

error_log  /var/log/nginx/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

pid        /var/run/nginx.pid;


events {
    worker_connections  2048;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$http_host" "$request" > "$upstream_addr" '
                      '$status $body_bytes_sent "$http_referer" '
                     '"$http_user_agent" "$http_x_forwarded_for"';
    #access_log  logs/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;

    # 关闭Nginx版本号显示
    server_tokens       off;

    proxy_buffering off;
    keepalive_timeout   300;
    keepalive_requests  200;
    client_max_body_size 20M;
    types_hash_max_size 2048;

    fastcgi_connect_timeout 300s;
    fastcgi_send_timeout 300s;
    fastcgi_read_timeout 300s;
    fastcgi_buffer_size 512k;
    fastcgi_buffers 10 512k;
    fastcgi_busy_buffers_size 1024k;
    fastcgi_temp_file_write_size 1024k;

    open_file_cache max=65535 inactive=60s;
    open_file_cache_valid 80s;
    server_names_hash_bucket_size 2048;
    client_header_buffer_size 128k;
    client_body_buffer_size 512k;
    large_client_header_buffers 4 128k;

    proxy_hide_header X-Powered-By;
    proxy_hide_header Server;
    proxy_connect_timeout 300;
    proxy_send_timeout 300;
    proxy_read_timeout 300;
    proxy_buffer_size 4k;
    proxy_buffers 4 64k;
    proxy_busy_buffers_size 128k;
    proxy_temp_file_write_size 128k;
    proxy_temp_path cache/mytemp_cache;
    proxy_cache_path cache/mytest_cache levels=1:2 keys_zone=mytest:20m inactive=24h max_size=1000m;
    proxy_intercept_errors on;

    gzip_min_length  1k;
    gzip_buffers     4 16k;
    gzip_comp_level  4;
    gzip_types      text/plain application/javascript image/png text/css text/xml text/vnd.wap.wml text/x-component application/x-javascript image/gif image/jpeg application/atom+xml application/rss+xml application/octet-stream application/x-rar-compressed application/json;
    gzip_http_version 1.1;
    gzip_vary on;
    gzip_disable "msie6";
    gzip  on;

    #请求限流
    limit_req_zone $binary_remote_addr zone=www_sym:10m rate=150r/s;
    limit_req_log_level error;    

    #连接数限流
    limit_conn_zone $binary_remote_addr zone=perip:10m;
    limit_conn_zone $server_name zone=perserver:10m;
    limit_conn_log_level error;
    
    #配置国家IP库
    geoip2 /usr/share/geoIP/GeoLite2-Country.mmdb {
      auto_reload 9m;
      $geoip2_country_name country names en;
      $geoip2_data_country_code country iso_code;
    }

    # 配置城市IP库
    geoip2 /usr/share/geoIP/GeoLite2-City.mmdb {
        auto_reload 5m;
        $geoip2_data_city_name city names en;
        $geoip2_data_province_name subdivisions 0 names en;
        $geoip2_data_province_isocode subdivisions 0 iso_code;
        $geoip2_continent_code continent code;
    }


    #国家IP过滤,只允许中国
    map $geoip2_data_country_code $allowed_country {
      default yes;
      CN no;
    }

    #设置白名单,在下列白名单中不限速
    geo $is_whitelist {
        default 0;
        172.17.0.0/16 1;
     }

     map $is_whitelist $limit_key {
         1 "";
         0 $binary_remote_addr;  
     } 

    server {
        listen       80;
        server_name www.icoding.fit;
        charset utf-8;
        client_max_body_size 300m;

        access_log  /var/log/nginx/www.icoding.fit.log  main;


        # 启用压缩,压缩等级为9级,压缩t
        gzip on;
        gzip_comp_level 9;
        gzip_types text/css text/plan text/xml application/javascript application/x-javascript application/html application/xml image/png image/jpg image/jpeg image/gif image/webp image/svg+xml;

        #限请求
        limit_req zone=www_sym burst=50 nodelay;
        #限流连接
        limit_conn perserver 500;
        limit_conn perip 150;

        # 如果超过设定的每秒150个连接数这个阈值,则返回448状态码给客户端
        limit_req_status 448;
   
        # 如果超过设定的每个IP每秒150个连接数这个阈值,则返回449状态码给客户端
        limit_conn_status 449;
   
        # 限制客户端速度只能到150k
        #limit_rate        150k;

        # 防盗链,如果请求的头不是test.if010.com就是无效的,则返回449状态码给客户端   
        #valid_referers none blocked test.if010.comm;
        #if ($invalid_referer) {
        #    return 449;
        #}

        # 做判断,如果国家不是中国,就返回451状态码给客户端;  
        if ($geoip2_data_country_code != CN ) {
            return 451;
        }
        
        # 添加客户端的IP头
        add_header client-country $geoip2_data_country_code;
        
        #限制国外IP
        if ($allowed_country = yes) {
           # return https://www.baidu.com;
           # return /home/japan;
           return 404;
        }

        # 防爬虫,如果UA是底下任意一个值,就判定为蜘蛛爬虫,则返回453给客户端
        if ($http_user_agent ~* "python|curl|java|wget|httpclient|okhttp|qihoobot|Scrubby|YodaoBot|yahoo-blogs/v3.9|Gigabot|yahoo-mmcrawler|Teoma|Robozilla|Bingbot|Slurp|Baiduspider|Googlebot|googlebot-mobile|googlebot-image|Mediapartners-Google|Adsbot-Google|Feedfetcher-Google|Yahoo!Slurp|Yahoo!Slurp China|YoudaoBot|Sosospider|MSNBot|ia_archiver|twiceler|psbot") {
            return 453;
        }

        location / {
            root   /N025/;
            index  index.html index.htm;
        }

        error_page  400 401 402 403 404 500 502 503 504 /error.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
        
    }

}

文章作者: 刘同学
本文链接:
版权声明: 本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 刘同学的小站
中间件 Nginx
喜欢就支持一下吧