您当前的位置:首页 > 电脑百科 > 站长技术 > 服务器

PHP+NGINX服务器性能安全优化

时间:2021-08-31 10:16:21  来源:  作者:wordpress建站

本文适用于 php7.4+Nginx环境,适用于运行 wordPress/ target=_blank class=infotextkey>WordPress 环境

一、更新服务器

sudo apt update

二、命令快捷缩写设置

通过ssh登录服务器,在用户目录下执行以下命令

sudo nano .bashrc
alias ngt='sudo nginx -t'
alias ngr='sudo systemctl reload nginx'
alias fpmr='sudo systemctl reload php7.4-fpm'
alias rr='sudo systemctl restart redis'
alias mdr='sudo systemctl restart mariadb'
alias rb='sudo reboot'
alias fup='sudo apt-get -y update;sudo apt-get -y full-upgrade;sudo apt-get -y autoremove; sudo apt-get -y autoclean'

按CTRL+S保存, CTRL+X退出

执行

source .bashrc

重启服务器使简化命令生效

后面要重启 nginx 或者 重载 nginx 只需要执行 ngt 或者 ngr 即可!

三、设置 nginx.conf

通常位于 /etc/nginx 目录下

# HTTP Header Server Delete for information leak
load_module modules/ngx_http_headers_more_filter_module.so;

# Run as a unique, less privileged user for security reasons.
# Default: nobody nobody
user www-data www-data;

# Sets the worker threads to the number of CPU cores available in the system for best performance.
# Should be > the number of CPU cores.
# Maximum number of connections = worker_processes * worker_connections
# Default: 1

worker_processes auto;

# Maximum number of open files per worker process.
# Should be > worker_connections.
# Default: no limit
worker_rlimit_nofile 15000;

events {
	# If you need more connections than this, you start optimizing your OS.
	# That's probably the point at which you hire people who are smarter than you as this is *a lot* of requests.
	# Should be < worker_rlimit_nofile.
	# Default: 512
	worker_connections 4096;
        multi_accept on;
        use epoll;
}

# Log errors to this file
# This is only used when you don't override it on a server{} level
# Default: logs/error.log error
error_log /var/log/nginx/error.log error;

# The file storing the process ID of the main process
# Default: nginx.pid
pid        /var/run/nginx.pid;

http {
	# Basic Settings
	server_tokens off;
	more_clear_headers 'Server';
	server_names_hash_bucket_size 64;

	# Webp Map Directives
	map $http_accept $webp_suffix {
  	default "";
  	"~*webp" ".webp";
	}

	# Specify MIME types for files.
	include       mime.types;

	# Rate Limit
	limit_req_zone $binary_remote_addr zone=one:10m rate=30r/m;
	
	# Default: text/plain
	default_type  Application/octet-stream;

	# Update charset_types to match updated mime.types.
	# text/html is always included by charset module.
	# Default: text/html text/xml text/plain text/vnd.wap.wml application/JAVAscript application/rss+xml
	charset_types
		text/css
		text/plain
		text/vnd.wap.wml
		application/JavaScript
		application/json
		application/rss+xml
		application/xml;

  	# Include $http_x_forwarded_for within default format used in log files
  	log_format main '$remote_addr - $remote_user [$time_local] "$request" '
					'$status $body_bytes_sent "$http_referer" '
					'"$http_user_agent" "$http_x_forwarded_for"';

	# Log access to this file
	# This is only used when you don't override it on a server{} level
	# Default: logs/access.log combined
        # access_log /var/log/nginx/access.log main;
	access_log none;

	# How long to allow each connection to stay idle.
	# Longer values are better for each individual client, particularly for SSL,
	# but means that worker connections are tied up longer.
	# Default: 75s
	keepalive_timeout 100s;
        keepalive_requests 1000;

	# Timeout for reading client request body.
	# Default: 60s
	client_body_timeout 3m;

	# Timeout for reading client request header.
	# Default: 60s
	client_header_timeout 3m;

	# Timeout for transmitting reponse to client.
	# Default: 60s
	send_timeout 3m;

	# Set the maximum allowed size of client request body. This should be set
	# to the value of files sizes you wish to upload to the server.
	# You may also need to change the values `upload_max_filesize` and `post_max_size` within
	# your php.ini for the changes to apply.
	# Default: 1mB
	client_max_body_size 64m;
	client_body_buffer_size 10k;
	client_header_buffer_size 1k;
	large_client_header_buffers 4 32k;

	# Some WP plugins that push large amounts of data via cookies
	# can cause 500 HTTP erros if these values aren't increased.
	# Default: 8 4k|8k;
	fastcgi_buffers 16 16k;
	
	# Default: 4k|8k
	fastcgi_buffer_size 32k;
	
	# Some other Fastcgi configs
	fastcgi_busy_buffers_size 64k;
	fastcgi_temp_file_write_size 64k;
	fastcgi_read_timeout 300;
	
	# File Handler Cache
	open_file_cache max=1500 inactive=30s;
	open_file_cache_valid 30s;
	open_file_cache_min_uses 5;
	open_file_cache_errors off;
	
	# Speed up file transfers by using sendfile() to copy directly
	# between descriptors rather than using read()/write().
	# For performance reasons, on FreeBSD systems w/ ZFS
	# this option should be disabled as ZFS's ARC caches
	# frequently used files in RAM by default.
	# Default: off
	sendfile        on;

	# Don't send out partial frames; this increases throughput
	# since TCP frames are filled up before being sent out.
	# Default: off
	tcp_nopush      on;

	# Enable gzip compression.
	# Default: off
	gzip on;
	gzip_disable "msie6";
	gzip_buffers 16 8k;
	gzip_http_version 1.1;
	# Compression level (1-9).
	# 5 is a perfect compromise between size and CPU usage, offering about
	# 75% reduction for most ASCII files (almost identical to level 9).
	# Default: 1
	gzip_comp_level    5;

	# Don't compress anything that's already small and unlikely to shrink much
	# if at all (the default is 20 bytes, which is bad as that usually leads to
	# larger files after gzipping).
	# Default: 20
	gzip_min_length    256;

	# Compress data even for clients that are connecting to us via proxies,
	# identified by the "Via" header (required for CloudFront).
	# Default: off
	gzip_proxied       any;

	# Tell proxies to cache both the gzipped and regular version of a resource
	# whenever the client's Accept-Encoding capabilities header varies;
	# Avoids the issue where a non-gzip capable client (which is extremely rare
	# today) would display gibberish if their proxy gave them the gzipped version.
	# Default: off
	gzip_vary          on;

	# Compress all output labeled with one of the following MIME-types.
	# text/html is always compressed by gzip module.
	# Default: text/html
	gzip_types
		application/atom+xml
		application/javascript
		application/json
		application/ld+json
		application/manifest+json
		application/rss+xml
		application/vnd.geo+json
		application/vnd.ms-fontobject
		application/x-font-ttf
		application/x-web-app-manifest+json
		application/xhtml+xml
		application/xml
		font/opentype
		image/bmp
		image/svg+xml
		image/x-icon
		text/cache-manifest
		text/css
		text/plain
		text/vcard
		text/vnd.rim.location.xloc
		text/vtt
		text/x-component
		text/x-cross-domain-policy;

	# This should be turned on if you are going to have pre-compressed copies (.gz) of
	# static files available. If not it should be left off as it will cause extra I/O
	# for the check. It is best if you enable this in a location{} block for
	# a specific directory, or on an individual server{} level.
	# gzip_static on;

	# Include files in the sites-enabled folder. server{} configuration files should be
	# placed in the sites-available folder, and then the configuration should be enabled
	# by creating a symlink to it in the sites-enabled folder.
	# See doc/sites-enabled.md for more info.
	include sites-enabled/*;
}

四、设置站点nginx配置 [防止攻击]

位置通常位于
/etc/nginx/sites-available/{{domain}}/server

1、新建 block-agent.conf

sudo nano block-agent.conf
###
# BLOCK USER AGENTS
###

set $block_user_agents 0;

if ($http_user_agent ~ "Screaming Frog seo Spider") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "Indy Library") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "libwww-perl") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "GetRight") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "GetWeb!") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "Go!Zilla") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "Download Demon") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "Go-Ahead-Got-It") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "TurnitinBot") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "GrabNet") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "dirbuster") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "nikto") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "SF") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "sqlmap") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "fimap") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "nessus") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "whatweb") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "Openvas") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "jbrofuzz") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "libwhisker") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "webshag") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "Acunetix-Product") {
    set $block_user_agents 1;
}
if ($http_user_agent ~ "Acunetix") {
    set $block_user_agents 1;
}
if ($block_user_agents = 1) {
    return 403;
}

2.新建
protext-sql-exploit-spam.conf

sudo nano protext-sql-exploit-spam.conf
###
# SQL INJECTIONS
###

set $block_sql_injections 0;

if ($query_string ~ "union.*select.*(") {
    set $block_sql_injections 1;
}
if ($query_string ~ "union.*all.*select.*") {
    set $block_sql_injections 1;
}
if ($query_string ~ "concat.*(") {
    set $block_sql_injections 1;
}
if ($block_sql_injections = 1) {
    return 403;
}



###
# COMMON EXPLOITS
###

set $block_common_exploits 0;

if ($query_string ~ "(<|%3C).*script.*(>|%3E)") {
    set $block_common_exploits 1;
}
if ($query_string ~ "GLOBALS(=|[|%[0-9A-Z]{0,2})") {
    set $block_common_exploits 1;
}
if ($query_string ~ "_REQUEST(=|[|%[0-9A-Z]{0,2})") {
    set $block_common_exploits 1;
}
if ($query_string ~ "proc/self/environ") {
    set $block_common_exploits 1;
}
if ($query_string ~ "mosConfig_[a-zA-Z_]{1,21}(=|%3D)") {
    set $block_common_exploits 1;
}
if ($query_string ~ "base64_(en|de)code(.*)") {
    set $block_common_exploits 1;
}
if ($block_common_exploits = 1) {
    return 403;
}



###
# BLOCK SPAM
###

set $block_spam 0;

if ($query_string ~ "b(ultram|unicauca|valium|viagra|vicodin|xanax|ypxaieo)b") {
    set $block_spam 1;
}
if ($query_string ~ "b(erections|hoodia|huronriveracres|impotence|levitra|libido)b") {
    set $block_spam 1;
}
if ($query_string ~ "b(ambien|bluespill|cialis|cocaine|ejaculation|erectile)b") {
    set $block_spam 1;
}
if ($query_string ~ "b(lipitor|phentermin|pro[sz]ac|sandyauer|tramadol|troyhamby)b") {
    set $block_spam 1;
}
if ($block_spam = 1) {
    return 403;
}

3、新建 rate-limit.conf

###
# Rate Limit for wp-login.php
###
# domain1不带.com后缀
# domain2 完整域名


location = /wp-login.php {
limit_req zone=one burst=2 nodelay;
limit_req_status 444;
include fastcgi.conf;
fastcgi_pass unix:/run/php/php7.4-{{domain1}}.sock;
include sites-available/{{domain2}}/location/*;
}

五、设置 redis

通常位于 /etc/redis/redis.conf

maxmemory 1024mb	
maxmemory-policy allkeys-lru

六、设置 wp-config.php

/* Memory */
define( 'WP_MEMORY_LIMIT', '1024M' );

/* Undertstand which query */
define('SAVEQUERIES', true);

/* Disable WP Cron */
define( 'DISABLE_WP_CRON', true );

/* Auto Update */
define( 'WP_AUTO_UPDATE_CORE', false );

/* Debuging */
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_DISPLAY', false );
define( 'WP_DEBUG_LOG', true );

/* Dont Allow File Edit */
define( 'DISALLOW_FILE_EDIT', true );

 

关于PHP设置,由于代码太长,不方便贴出来。下一遍我们将会把以上代码做成sh文件,一键自动执行优化。



Tags:服务器   点击:()  评论:()
声明:本站部分内容及图片来自互联网,转载是出于传递更多信息之目的,内容观点仅代表作者本人,如有任何标注错误或版权侵犯请与我们联系(Email:2595517585@qq.com),我们将及时更正、删除,谢谢。
▌相关推荐
Windows操作系统和Linux操作系统有何区别?Windows操作系统:需支付版权费用,(华为云已购买正版版权,在华为云购买云服务器的用户安装系统时无需额外付费),界面化的操作系统对用户使...【详细内容】
2021-12-21  Tags: 服务器  点击:(6)  评论:(0)  加入收藏
以下是服务器安全加固的步骤,本文以腾讯云的CentOS7.7版本为例来介绍,如果你使用的是秘钥登录服务器1-5步骤可以跳过。1、设置复杂密码服务器设置大写、小写、特殊字符、数字...【详细内容】
2021-12-20  Tags: 服务器  点击:(7)  评论:(0)  加入收藏
转自: https://kermsite.com/p/wt-ssh/由于格式问题,部分链接、表格可能会失效,若失效请访问原文密码登录 以及 通过密钥实现免密码登录Dec 15, 2021阅读时长: 6 分钟简介Windo...【详细内容】
2021-12-17  Tags: 服务器  点击:(16)  评论:(0)  加入收藏
简介在之前的文章中,我们提到了在netty的客户端通过使用Http2FrameCodec和Http2MultiplexHandler可以支持多路复用,也就是说在一个连接的channel基础上创建多个子channel,通过...【详细内容】
2021-12-14  Tags: 服务器  点击:(6)  评论:(0)  加入收藏
阿里云和腾讯云都是非常好的云服务器平台,大多数用户完全不用纠结腾讯云还是阿里云,特别是微信开发用户,自然是首选腾讯云,其次是学生或个人以及财政紧张的小公司微型业务,腾讯云...【详细内容】
2021-12-14  Tags: 服务器  点击:(14)  评论:(0)  加入收藏
今日总监说32 服务器 磁盘占用率 超过80%多了 。不对啊 之前才清理过df -h 查看了一番 果然40g 用了33g。看了下历史会爆目录 也就5.3G 之前是服务生成临时下载的附件多。...【详细内容】
2021-12-10  Tags: 服务器  点击:(16)  评论:(0)  加入收藏
在Linux系统下如何分享文件呢,你可能会想到用scp、rsync此类的命令,但都需要给出服务器密码,不安全。或者搭建一个ftp、nfs或samba的服务,分配个账号或划分个权限给其它人共享文...【详细内容】
2021-12-08  Tags: 服务器  点击:(14)  评论:(0)  加入收藏
域名系统是最重要的互联网服务之一,没有它,我们将无法访问在线内容,甚至无法发送电子邮件。每当我们尝试连接到其他网站或在线服务时,根 DNS 服务器都会帮助我们的计算机找到并...【详细内容】
2021-11-25  Tags: 服务器  点击:(35)  评论:(0)  加入收藏
实验拓扑 图 1-1实验需求 在深圳总部的 AF 上,配置 DDOS 防护,防止服务器区的服务器被 DDOS 攻击 在深圳总部的 AF 上,配置 IPS,对服务器区的服务器实现入侵检测和入侵防御实验...【详细内容】
2021-11-23  Tags: 服务器  点击:(26)  评论:(0)  加入收藏
服务器日志(server log)是一个或多个由服务器自动创建和维护的日志文件,其中包含其所执行活动的列表简单来说,服务器的日记就是记录网站被访问的全过程,什么时间到什么时间有哪...【详细内容】
2021-11-11  Tags: 服务器  点击:(41)  评论:(0)  加入收藏
▌简易百科推荐
阿里云镜像源地址及安装网站地址https://developer.aliyun.com/mirror/centos?spm=a2c6h.13651102.0.0.3e221b111kK44P更新源之前把之前的国外的镜像先备份一下 切换到yumcd...【详细内容】
2021-12-27  干程序那些事    Tags:CentOS7镜像   点击:(1)  评论:(0)  加入收藏
前言在实现TCP长连接功能中,客户端断线重连是一个很常见的问题,当我们使用netty实现断线重连时,是否考虑过如下几个问题: 如何监听到客户端和服务端连接断开 ? 如何实现断线后重...【详细内容】
2021-12-24  程序猿阿嘴  CSDN  Tags:Netty   点击:(12)  评论:(0)  加入收藏
一. 配置yum源在目录 /etc/yum.repos.d/ 下新建文件 google-chrome.repovim /etc/yum.repos.d/google-chrome.repo按i进入编辑模式写入如下内容:[google-chrome]name=googl...【详细内容】
2021-12-23  有云转晴    Tags:chrome   点击:(7)  评论:(0)  加入收藏
一. HTTP gzip压缩,概述 request header中声明Accept-Encoding : gzip,告知服务器客户端接受gzip的数据 response body,同时加入以下header:Content-Encoding: gzip:表明bo...【详细内容】
2021-12-22  java乐园    Tags:gzip压缩   点击:(8)  评论:(0)  加入收藏
yum -y install gcc automake autoconf libtool makeadduser testpasswd testmkdir /tmp/exploitln -s /usr/bin/ping /tmp/exploit/targetexec 3< /tmp/exploit/targetls -...【详细内容】
2021-12-22  SofM    Tags:Centos7   点击:(7)  评论:(0)  加入收藏
Windows操作系统和Linux操作系统有何区别?Windows操作系统:需支付版权费用,(华为云已购买正版版权,在华为云购买云服务器的用户安装系统时无需额外付费),界面化的操作系统对用户使...【详细内容】
2021-12-21  卷毛琴姨    Tags:云服务器   点击:(6)  评论:(0)  加入收藏
参考资料:Hive3.1.2安装指南_厦大数据库实验室博客Hive学习(一) 安装 环境:CentOS 7 + Hadoop3.2 + Hive3.1 - 一个人、一座城 - 博客园1.安装hive1.1下载地址hive镜像路径 ht...【详细内容】
2021-12-20  zebra-08    Tags:Hive   点击:(9)  评论:(0)  加入收藏
以下是服务器安全加固的步骤,本文以腾讯云的CentOS7.7版本为例来介绍,如果你使用的是秘钥登录服务器1-5步骤可以跳过。1、设置复杂密码服务器设置大写、小写、特殊字符、数字...【详细内容】
2021-12-20  网安人    Tags:服务器   点击:(7)  评论:(0)  加入收藏
项目中,遇到了一个问题,就是PDF等文档不能够在线预览,预览时会报错。错误描述浏览器的console中,显示如下错误:nginx代理服务报Mixed Content: The page at ******** was loaded...【详细内容】
2021-12-17  mdong    Tags:Nginx   点击:(7)  评论:(0)  加入收藏
转自: https://kermsite.com/p/wt-ssh/由于格式问题,部分链接、表格可能会失效,若失效请访问原文密码登录 以及 通过密钥实现免密码登录Dec 15, 2021阅读时长: 6 分钟简介Windo...【详细内容】
2021-12-17  LaLiLi    Tags:SSH连接   点击:(16)  评论:(0)  加入收藏
最新更新
栏目热门
栏目头条