一、背景介绍

Nginx (engine x) 是一个高性能的HTTP和反向代理web服务器,同时也提供了IMAP/POP3/SMTP服务。

二、安装

  1. $ wget http://nginx.org/download/nginx-1.14.2.tar.gz
  2. # 解压源码
  3. $ tar -zxvf nginx-1.14.2.tar.gz
  4. # 进入源码目录
  5. $ cd nginx-1.14.2
  6. $ ./configure
  7. --prefix=/usr/local/nginx --with-http_ssl_module --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --add-module=/usr/local/src/ModSecurity-nginx
  8. $ make
  9. $ make install

四、配置

1)、创建目录

  • 日志目录 /www/logs/nginx/
  • 证书目录 /usr/local/nginx/ssl/

    1. 要把证书放入到上诉目录

    2)、主配置文件

    ```bash

user www www; worker_processes 8;

pid /var/run/nginx.pid;

worker_rlimit_nofile 65535;

events { worker_connections 65535; }

http {

  1. charset utf-8;
  2. include mime.types;
  3. default_type application/octet-stream;
  4. log_format main escape=json '$remote_addr - $remote_user [$time_local] "$request" '
  5. '$status $body_bytes_sent "$http_referer" '
  6. '"$http_user_agent" "$http_x_forwarded_for" "$request_time" "$request_body" "$host"';
  7. error_log logs/nginx_error.log error;
  8. #proxy_ignore_client_abort on;
  9. proxy_buffering off;
  10. server_names_hash_bucket_size 128;
  11. client_header_buffer_size 128k;
  12. large_client_header_buffers 4 128k;
  13. client_max_body_size 100m;
  14. client_body_buffer_size 1024k;
  15. ssl_session_cache shared:SSL:10m;
  16. ssl_session_timeout 10m;
  17. sendfile on;
  18. tcp_nopush on;
  19. keepalive_timeout 65;
  20. tcp_nodelay on;
  21. fastcgi_intercept_errors on;
  22. fastcgi_connect_timeout 300;
  23. fastcgi_send_timeout 300;
  24. fastcgi_read_timeout 300;
  25. fastcgi_buffer_size 128k;
  26. fastcgi_buffers 4 128k;
  27. fastcgi_busy_buffers_size 128k;
  28. fastcgi_temp_file_write_size 128k;
  29. gzip on;
  30. gzip_min_length 1k;
  31. gzip_buffers 4 16k;
  32. gzip_http_version 1.0;
  33. gzip_comp_level 2;
  34. gzip_types text/plain application/x-javascript text/css application/xml image/jpeg image/gif image/png;
  35. gzip_vary on;
  36. server_tokens off;
  37. proxy_hide_header X-Powered-By;
  38. proxy_hide_header Server;
  39. fastcgi_hide_header X-Powered-By;

include conf.d/*.conf; }

  1. <a name="tx50v"></a>
  2. ## 3)、报错设置
  3. 初期调试时,请不要调整到指定的5xx页面
  4. ```bash
  5. error_page 500 502 503 504 /50x.html;

4)、子域名

server {
    listen 80;
    listen 443 ssl;
    #域名配置
    server_name subdomain.domain.com;
    #根目录
    root /www/domain/public;
    index index.php index.html;
    # 没搞明白这里为啥是关闭

    ssl off;
    # 证书
    ssl_certificate /usr/local/nginx/ssl/domain.com.pem;
    ssl_certificate_key /usr/local/nginx/ssl/domain.com.key;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;

    if ($host !~* ^(.*)\.domain\.com$) {
       return 403;
    }

    # enable HSTS
    #add_header Strict-Transport-Security "max-age=31536000; includeSubDomains;preload" always;

    #if ($scheme = http) {
    #     return 301 https://$host$request_uri;
    #}

    if ($time_iso8601 ~ "^(\d{4}-\d{2}-\d{2})") {
        set $year $1;
        set $month $2;
        set $day $3;
    }

    access_log /www/logs/nginx/domain_access_$year-$month-$day.log main;
    error_log  /www/logs/nginx/domain_error.log error;
# 配置php部分
    location / {
        try_files $uri $uri/ /index.php?$query_string;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    location ~* \.php$ {
        fastcgi_index  index.php;
        fastcgi_pass   127.0.0.1:9000;
        include        fastcgi_params;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_param   SCRIPT_NAME        $fastcgi_script_name;
    }

    }

配置日志按天存放

a、直接拷贝报错1

里面有的空格格式不对

[root@ nginx]# /usr/local/nginx/sbin/nginx -t
nginx: [emerg] unknown directive " " in /usr/local/nginx/conf/conf/www.bjpxw.com.conf:14
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed

b、变量重复定义

变量名重复了。重新修改变量名就可以

[root@zjt-ecs-1 nginx]# /usr/local/nginx/sbin/nginx -t
nginx: [emerg] the duplicate "year" variable in /usr/local/nginx/conf/conf/www.bjpxw.com.conf:14

5)、 隐藏nginx和php版本号

下列代码添加到nginx.conf的http段

server_tokens off;

隐藏php的版本号

下列代码添加到nginx.conf的http段

fastcgi_hide_header X-Powered-By;

6)、 根据ua设置403

必须添加到SEVER段

 #user_agent设置
    if ($http_user_agent ~ 'curl|baidu|1111')
    {
       return 403;
    }

五、启动-停止

#启动
$ /usr/local/nginx/sbin/nginx

#停止
$ /usr/local/nginx/sbin/nginx -s stop

#重启
$ /usr/local/nginx/sbin/nginx -s reload

六、服务管理

需要配置服务管理文件

1)、创建nginx.service

vim /usr/lib/systemd/system/nginx.service

2)、设置内容如下

[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/run/nginx.pid
# Nginx will fail to start if /run/nginx.pid already exists but has the wrong
# SELinux context. This might happen when running `nginx -t` from the cmdline.
# https://bugzilla.redhat.com/show_bug.cgi?id=1268621
ExecStartPre=/usr/bin/rm -f /run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true

[Install]
WantedBy=multi-user.target

3)、使文件生效

systemctl daemon-reload

4)、常用命令

启动
systemctl start nginx

关闭nginx
systemctl stop nginx

重启nginx
systemctl restart nginx

5)、开机启动

systemctl enable nginx

7、排错

1)、端口被占用

[root@zjt-baidu nginx-1.14.2]# /usr/local/nginx/sbin/nginx
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)

使用ps axf 看看

[root@zjt-baidu ~]# ps axf | grep nginx
 2969 pts/2    S+     0:00          \_ grep --color=auto nginx
 1295 ?        Ss     0:00 nginx: master process /usr/sbin/nginx
 1296 ?        S      0:00  \_ nginx: worker process
 1297 ?        S      0:00  \_ nginx: worker process

不过这个是不严谨的,因为有的时候,会是别的应用程序占用了80端口
那查看端口占用情况

[root@zjt-baidu ~]# netstat -ntlup | grep 80
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1295/nginx: master  
tcp6       0      0 :::80                   :::*                    LISTEN      1295/nginx: master

结束掉相应的进程

2)、配置文件出错

[root@zjt-baidu ~]# /usr/local/nginx/sbin/nginx -s stop
nginx: [emerg] unexpected "}" in /usr/local/nginx/conf/nginx.conf:149

缺少分号

    #}
 include conf.d/*.conf

}

八、负载配置

配置代码

#user  nobody;
worker_processes  1;

#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 {
    #集群配置
    upstream am{

        server 1111:8088 max_fails=1 fail_timeout=30s;
        server 1111:8088 max_fails=1 fail_timeout=30s;
    }

    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" "$upstream_addr"';

    access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    #代理
    server {
        listen       10000;
        server_name  111.11.11.10;

        #access_log  logs/host.access.log  main;

        location /am {
            proxy_next_upstream error  timeout invalid_header  http_500  http_502 http_503  http_504  http_403  http_404  http_429; 
            proxy_set_header  Host $host:$server_port;
            proxy_set_header  X-Forwarded-Port $server_port;
            proxy_set_header  X-Real-IP $remote_addr;
            proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header  X-Forwarded-Proto $scheme;
            proxy_pass http://am;
        }

    }

}

九、sub_filter模块之字符串替换与内容过滤

sub_filter模块可以用在nginx的http、server、location模块中,主要作用就是查找替换文件字符。如我们用模板生成网站的静态文件,因为疏漏或者别的原因造成代码不如意,但是此时因为文件数量巨大,不方便全部重新生成,那么这个时候我们就可以用此模块来暂时实现纠错。又如网站更换域名,其中的附件全是用的就域名地址,重新修改内容显然太麻烦……

常用代码

1 proxy_set_header Accept-Encoding ‘’;#替换gzip需要加上这句 1 proxy_set_header Accept-Encoding ‘’;#替换gzip需要加上这句
2 sub_filter_types *;#可不加,每日就是替换文本类型 2 sub_filter_types *;#可不加,每日就是替换文本类型
3 sub_filter_once off;#默认是on,只替换一次 3 sub_filter_once off;#默认是on,只替换一次
4 sub_filter ‘www.800m.net’ ‘800m.net’;#域名替换、字符串替换 4 sub_filter ‘www.800m.net’ ‘800m.net’;#域名替换、字符串替换

加入位置

1、在server中直接加入
2、在location中加入,反代也可以替换。

1 location ~ .*$ { 1 location ~ .*$ {
2 proxy_set_header Host nginx.800m.net; 2 proxy_set_header Host nginx.800m.net;
3 proxy_pass http://nginx.800m.net; 3 proxy_pass http://nginx.800m.net;
4 sub_filter_types *; 4 sub_filter_types *;
5 sub_filter_once off; 5 sub_filter_once off;
6 sub_filter ‘nginx.800m.net’ ‘apche.800m.net’; 6 sub_filter ‘nginx.800m.net’ ‘apche.800m.net’;
7 } 7 }