nginx安装及安全配置和转发代理

 

Nginx安装

1. 新建用户和组 ngxuser:ngxuser

groupadd ngxuser 

useradd -m -g ngxuser ngxuser  #-m自动建立家目录,-g指定组

2. 安装依赖包(nginx安装都是用root用户装哦)

红色遮住的两个不需要装

#强制全部安装

rpm -Uvh *.rpm --nodeps --force

#单独安装rpm方式

rpm -ivh libmpc-1.0.1-3.el7.x86_64.rpm

#如果有相互依赖关系也可以一次安装多个,例如:

rpm -ivh glibc-2.17-317.el7.x86_64.rpm glibc-common-2.17-317.el7.x86_64.rpm

查看GCC版本: gcc  -v

3. 安装pcre

tar -zxvf pcre-8.35.tar.gz

cd pcre-8.35

./configure

make && make install

查看pcre版本: rpm -qa pcre

4.安装zlib

tar -zxvf zlib-1.2.11.tar.gz

cd zlib-1.2.11

./configure

make && make install

5. 安装openssl

tar -zxvf openssl-1.1.1j.tar.gz
cd openssl-1.1.1j.tar
./config shared zlib --prefix=/usr/local/openssl
make
make install

成功以后可以查看openssl的版本

命令:openssl  version  或者 openssl  version -a

6.安装nginx

此处注意pcre,zlib,ssl的路径,我是把ngxin、pcre、zlib、ssl的安装包都放在了/usr/local/下面

tar -zxvf nginx-1.18.0.tar.gz

cd nginx-1.18.0

./configure --user=ngxuser --group=ngxuser --prefix=/usr/local/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --pid-path=/usr/local/nginx/logs/nginx.pid --with-http_stub_status_module --with-pcre=/usr/local/pcre-8.35 --with-zlib=/usr/local/zlib-1.2.11 --with-http_ssl_module --with-openssl=/usr/local/openssl-1.1.1j

make && make install

执行make && make install时间可能比较久,耐心等待即可,出现以下信息表明安装完成

#配置概要,出现以下信息说明安装成功
Configuration summary 
  + using PCRE library: /usr/local/pcre-8.35
  + using OpenSSL library: /usr/local/openssl-1.1.1j
  + using zlib library: /usr/local/zlib-1.2.11

  nginx path prefix: "/usr/local/nginx"
  nginx binary file: "/usr/local/nginx/sbin/nginx"
  nginx modules path: "/usr/local/nginx/modules"
  nginx configuration prefix: "/usr/local/nginx-1.18.0/conf"
  nginx configuration file: "/usr/local/nginx-1.18.0/conf/nginx.conf"
  nginx pid file: "/usr/local/nginx/logs/nginx.pid"
  nginx error log file: "/usr/local/nginx/logs/error.log"
  nginx http access log file: "/usr/local/nginx/logs/access.log"
  nginx http client request body temporary files: "client_body_temp"
  nginx http proxy temporary files: "proxy_temp"
  nginx http fastcgi temporary files: "fastcgi_temp"
  nginx http uwsgi temporary files: "uwsgi_temp"
  nginx http scgi temporary files: "scgi_temp"

7.测试

到这一步其实nginx已经安装完成,可以启动nginx,并用浏览器访问一下测试效果;

启动nginx
cd /usr/local/nginx/sbin
#检查配置,如果无报错即可启动,有报错继续排查错误
./nginx -t
#启动nginx
./nginx
#重新加载nginx,修改配置后不用重启应用,服务不中断
./nginx -s reload
#停止nginx
./nginx -s quit
#强制停止nginx
./nginx -s stop

ssl密钥如果需要可以自己配置,在测试环境我自己生成了一个测试密钥,放在了下面的路径

cd  /usr/local/nginx/conf

mkdir ssl

然后把SSL授权文件放到/usr/local/nginx/conf/ssl路径下

8.ngxin.conf配置,这一步很重要,配置错误ngxin就起不来哦

#使用ngxuser用户组的ngxuser用户运行nginx的worker进程
user ngxuser ngxuser;

#工作进程数CPU是几进程就配置为几进程
worker_processes  1;

#进程pid文件
pid /usr/local/nginx/logs/nginx.pid;

events {
    #最大允许建立的外部链接数量1024个连接大约占内存1024*328/1024/1024=0.32M
    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"';

    sendfile        on;
    #tcp_nopush     on;
    keepalive_timeout  65;

    gzip  on;

        #被代理的地址和端口
        upstream my_server {
                server 86.10.8.214:8081;
                server 86.10.8.213:8081 backup;                
        }
    
    # HTTP server
    server {
        listen 8080;
                server_name 86.10.8.212;
                
                #防止慢型http拒绝服务攻击
                client_header_timeout 10s;
                client_header_buffer_size 1k;
                large_client_header_buffers 4 1k;
                
                client_body_timeout 10s;
                client_body_buffer_size 1M;
                client_body_temp_path /usr/local/nginx/client_body_temp/;
                client_max_body_size 3M;                           
                
                include       mime.types;
                server_tokens off;  #隐藏版本号
                
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header REMOTE-HOST $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;     
                proxy_set_header Host $host;
               # 响应头缺失漏洞,安全策略,简单的XSS攻击防护配置
               add_header X-Frame-Options 'SAMEORIGIN'; #只允许本网站的frame嵌套       
                add_header Content-Security-Policy "default-src 'self';script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src * data:; style-src 'self' 'unsafe-inline';";  #仅允许加载同源的文件
                add_header X-XSS-Protection '1;mode=block'; #开启XSS过滤器
                add_header X-Content-Type-Options nosniff; #禁止嗅探文件类型
                add_header Referrer-Policy 'strict-origin-when-cross-origin';
                add_header X-Download-Options noopen;
            # SQL注入漏洞
            if ($request_method !~* GET|POST) { return 444; } 
                #使用444错误代码可以更加减轻服务器负载压力。 
                #防止SQL注入 
                if ($query_string ~* (\$|'|--|[+|(%20)]union[+|(%20)]|[+|(%20)]insert[+|(%20)]|[+|(%20)]drop[+|(%20)]|[+|(%20)]truncate[+|(%20)]|[+|(%20)]update[+|(%20)]|[+|(%20)]from[+|(%20)]|[+|(%20)]grant[+|(%20)]|[+|(%20)]exec[+|(%20)]|[+|(%20)]where[+|(%20)]|[+|(%20)]select[+|(%20)]|[+|(%20)]and[+|(%20)]|[+|(%20)]or[+|(%20)]|[+|(%20)]count[+|(%20)]|[+|(%20)]exec[+|(%20)]|[+|(%20)]chr[+|(%20)]|[+|(%20)]mid[+|(%20)]|[+|(%20)]like[+|(%20)]|[+|(%20)]iframe[+|(%20)]|[\<|%3c]script[\>|%3e]|javascript|alert|webscan|dbappsecurity|style|confirm\(|innerhtml|innertext)(.*)$) { return 555; }
                if ($uri ~* (/~).*) { return 501; } 
                if ($uri ~* (\\x.)) { return 501; } 
                #防止SQL注入 
                if ($query_string ~* "[;'<>].*") { return 509; } 
                if ($request_uri ~ " ") { return 509; } 
                if ($request_uri ~ (\/\.+)) { return 509; } 
                if ($request_uri ~ (\.+\/)) { return 509; } 
                #if ($uri ~* (insert|select|delete|update|count|master|truncate|declare|exec|\*|\')(.*)$ ) { return 503; } #防止SQL注入 
                if ($request_uri ~* "(cost\()|(concat\()") { return 504; } 
                if ($request_uri ~* "[+|(%20)]union[+|(%20)]") { return 504; } 
                if ($request_uri ~* "[+|(%20)]and[+|(%20)]") { return 504; } 
                if ($request_uri ~* "[+|(%20)]select[+|(%20)]") { return 504; } 
                if ($request_uri ~* "[+|(%20)]or[+|(%20)]") { return 504; } 
                if ($request_uri ~* "[+|(%20)]delete[+|(%20)]") { return 504; } 
                if ($request_uri ~* "[+|(%20)]update[+|(%20)]") { return 504; } 
                if ($request_uri ~* "[+|(%20)]insert[+|(%20)]") { return 504; } 
                if ($query_string ~ "(<|%3C).*script.*(>|%3E)") { return 505; } 
                if ($query_string ~ "GLOBALS(=|\[|\%[0-9A-Z]{0,2})") { return 505; } 
                if ($query_string ~ "_REQUEST(=|\[|\%[0-9A-Z]{0,2})") { return 505; } 
                if ($query_string ~ "proc/self/environ") { return 505; } 
                if ($query_string ~ "mosConfig_[a-zA-Z_]{1,21}(=|\%3D)") { return 505; } 
                if ($query_string ~ "base64_(en|de)code\(.*\)") { return 505; } 
                if ($query_string ~ "[a-zA-Z0-9_]=http://") { return 506; } 
                if ($query_string ~ "[a-zA-Z0-9_]=(\.\.//?)+") { return 506; } 
                if ($query_string ~ "[a-zA-Z0-9_]=/([a-z0-9_.]//?)+") { return 506; } 
                if ($query_string ~ "b(ultram|unicauca|valium|viagra|vicodin|xanax|ypxaieo)b") { return 507; } 
                if ($query_string ~ "b(erections|hoodia|huronriveracres|impotence|levitra|libido)b") {return 507; } 
                if ($query_string ~ "b(ambien|bluespill|cialis|cocaine|ejaculation|erectile)b") { return 507; } 
                if ($query_string ~ "b(lipitor|phentermin|pro[sz]ac|sandyauer|tramadol|troyhamby)b") { return 507; }
                 #这里大家根据自己情况添加删减上述判断参数,cURL、wget这类的屏蔽有点儿极端了,但要“宁可错杀一千,不可放过一个”。 
                if ($http_user_agent ~* YisouSpider|ApacheBench|WebBench|Jmeter|JoeDog|Havij|GetRight|TurnitinBot|GrabNet|masscan|mail2000|github|wget|curl|Java|python) { return 508; } 
                #同上,大家根据自己站点实际情况来添加删减下面的屏蔽拦截参数。 
                if ($http_user_agent ~* "Go-Ahead-Got-It") { return 508; } 
                if ($http_user_agent ~* "GetWeb!") { return 508; } 
                if ($http_user_agent ~* "Go!Zilla") { return 508; } 
                if ($http_user_agent ~* "Download Demon") { return 508; } 
                if ($http_user_agent ~* "Indy Library") { return 508; } 
                if ($http_user_agent ~* "libwww-perl") { return 508; } 
                if ($http_user_agent ~* "Nmap Scripting Engine") { return 508; } 
                if ($http_user_agent ~* "~17ce.com") { return 508; } 
                if ($http_user_agent ~* "WebBench*") { return 508; } 
                #这个会影响国内某些搜索引擎爬虫,比如:搜狗 
                if ($http_user_agent ~* "spider") { return 508; } 
                #拦截各恶意请求的UA,可以通过分析站点日志文件或者waf日志作为参考配置。
                if ($http_referer ~* 17ce.com) { return 509; } 
                #拦截17ce.com站点测速节点的请求,所以明月一直都说这些测速网站的数据仅供参考不能当真的。 
                if ($http_referer ~* WebBench*") { return 509; } 
                #拦截WebBench或者类似压力测试工具,其他 工具 只需要更换名称即可。

                 #防盗链,需要修改网址
                 #注意!代理防盗链和本地服务器防盗链时不一样的配置哦,我这台服务器仅仅用于代理,没有放静态资源,如果有静态资源可以修改root路径
                location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)$ {
                        expires 30d; 
                        access_log off;
                        valid_referers none blocked 86.10.8.237 86.10.8.213 *.domain.cn domain.cn;
                        if ($invalid_referer) {
                            return 403;
                            #rewrite ^/ http://domain.cn/image/404.jpg;
                        }
                        
                        proxy_pass http://my_server;
                    }
        
        location / { 
                        
                proxy_pass http://my_server/;    
                proxy_redirect off;
  
                #proxy_redirect http://my_server/myApp/ http://$host:$server_port/;
            }                  
        }
}

 9.设置nginx开机启动

1.编辑nginx.service文件,从某个版本(忘了哪个了)开始CentOS的开机加载策略有变化,不要用错了哦,我的是CentOS7.4

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

把下面的内容粘贴到nginx.service里面

[Unit]
Description=nginx
After=network.target
  
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid #这里不要少哦,否则会有问题哦,我就在这里绕了很大的弯路,最后看linux手册才找到问题
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true
  
[Install]
WantedBy=multi-user.target

[Unit]:服务的说明

Description:描述服务

After:描述服务类别

[Service]服务运行参数的设置

Type=forking是后台运行的形式

ExecStart为服务的具体运行命令

ExecReload为重启命令

ExecStop为停止命令

PrivateTmp=True表示给服务分配独立的临时空间

注意:[Service]的启动、重启、停止命令全部要求使用绝对路径

[Install]运行级别下服务安装的相关设置,可设置为多用户,即系统运行级别为3

2.设置开机自启动

systemctl start nginx.service   #启动服务

systemctl enable nginx.service   #开机自启动

systemctl daemon-reload   #如果之前设置失败后再次设置时先执行此命令重新加载daemon,然后在执行enable;

设置开机启动以后检查一下是否设置成功 

systemctl  list-unit-files | grep enabled

#常用命令

systemctl status nginx.service #查看nginx状态

systemctl start nginx.service #启动nginx

systemctl stop nginx.service #停止nginx

systemctl reload nginx.service #重启nginx,这个命令会很常用哦

10.隐藏nginx的response头中的Server字段

1. 停止nginx服务,进入nginx源码目录(不是安装目录,是安装前解压的那个目录);
2. vi src/http/ngx_http_header_filter_module.c  #49-50行 (HTTP ResponseHeader响应头)
原内容:
static char ngx_http_server_string[] = "Server: nginx" CRLF;
static char ngx_http_server_full_string[] = "Server: " NGINX_VER CRLF;
更改为:
static char ngx_http_server_string[] = "Server:myServerName" CRLF;
static char ngx_http_server_full_string[] = "Server:myServerName " CRLF;

3. vi src/core/nginx.h (Nginx内部名称的)
修改,不要删前面的#:
#define NGINX_VERSION “1.0″    
#define NGINX_VER “myServerName/” NGINX_VERSION

4. vi src/http/ngx_http_special_response.c(错误页的底部Footer)

设置完以后还得重新安装一遍nginx,

./configure --user=ngxuser --group=ngxuser --prefix=/usr/local/nginx --conf-path=/usr/local/nginx/conf/nginx.conf --pid-path=/usr/local/nginx/logs/nginx.pid --with-http_stub_status_module --with-pcre=/usr/local/pcre-8.35 --with-zlib=/usr/local/zlib-1.2.11 --with-http_ssl_module --with-openssl=/usr/local/openssl-1.1.1j

安装并编译
make && make install

11.Linux安全设置设置

  1.防火墙设置

查看防火墙状态
systemctl status firewalld
打开防火墙
systemctl start firewalld
关闭防火墙
systemctl stop firewalld
开机启动防火墙
systemctl enable firewalld
systemctl is -enable firewalld #查看是否开机启动
关闭开机启动防火墙
systemctl disable firewalld

设置策略和端口,只打开需要的端口和请求协议
sudo firewall-cmd --zone=public --permanent --add-service=https
firewall-cmd --zone=public --add-port=443/tcp --permanent
重新加载策略
sudo firewall-cmd --reload

查看防火墙打开的所有服务是否开启HTTP服务。
sudo firewall-cmd --list-service

2. linux禁止root用户登录,这个我设置了,但是没用上,因为nginx必须root用户启动

禁止root用户登录,只允许普通用户使用su切换到root;

我们已经创建了ngxuser用户,下面创建用户的步骤不用执行

    1)创建普通用户: useradd ngxuser

    2)设置密码: passwd ngxuser

    3)禁止root用户登录

    vi /etc/ssh/sshd_config

    PermitRootLogin no

    然后执行

systemctl restart sshd

如果要改过来只需要注释掉PermitRootLogin即可

vi /etc/ssh/sshd_config

#PermitRootLogin no

然后执行

systemctl restart sshd

 

3.修改ssh默认端口22

以下将端口改为56588可以根据需要自己更改,最好选择10000-65535内的端口

查看端口是否被占用

 netstat -lnp | grep 56588

 

1. 修改/etc/ssh/sshd_config

    vi /etc/ssh/sshd_config   

Port 22 //这里不删除 22 端口是为了防止修改后新端口无法访问,造成无法用 ssh 连接服务器。)

Port 56588

 

2. 设置防火墙通过端口

firewall-cmd --zone=public --add-port=56588/tcp --permanent

重新加载策略

sudo firewall-cmd --reload

查询端口是否开启

firewall-cmd --permanent --query-port=56588/tcp

3.修改SELinux

  1. 查看seLinux状态

sestatus

2)开启关闭seLinux

setenforce 1  #0:关闭,1:是开启

3)查看seLinux开放的端口

semanage port -l | grep ssh

4)添加新端口

semanage port -a -t ssh_port_t -p tcp 56588

5)修改保存重启sshd服务

systemctl restart sshd   #systemctl restart sshd.service

6)关闭22端口

vi /etc/ssh/sshd_config

#Port 22

Port 56588

防火墙删除开放端口

firewall-cmd --zone=public --remove-port=22/tcp --permanent

重新加载策略

sudo firewall-cmd --reload

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值