详解nginx服务器中的安全配置

2019-10-17 19:15:35丽君

十四、Nginx与PHP安全建议
PHP是流行的服务器端脚本语言之一。如下编辑/etc/php.ini文件:

# Disallow dangerous functions
disable_functions = phpinfo, system, mail, exec
## Try to limit resources ##
# Maximum execution time of each script, in seconds
max_execution_time = 30
# Maximum amount of time each script may spend parsing request data
max_input_time = 60
# Maximum amount of memory a script may consume (8MB)
memory_limit = 8M
# Maximum size of POST data that PHP will accept.
post_max_size = 8M
# Whether to allow HTTP file uploads.
file_uploads = Off
# Maximum allowed size for uploaded files.
upload_max_filesize = 2M
# Do not expose PHP error messages to external users
display_errors = Off
# Turn on safe mode
safe_mode = On
# Only allow access to executables in isolated directory
safe_mode_exec_dir = php-required-executables-path
# Limit external access to PHP environment
safe_mode_allowed_env_vars = PHP_
# Restrict PHP information leakage
expose_php = Off
# Log all errors
log_errors = On
# Do not register globals for input data
register_globals = Off
# Minimize allowable PHP post size
post_max_size = 1K
# Ensure PHP redirects appropriately
cgi.force_redirect = 0
# Disallow uploading unless necessary
# Enable SQL safe mode
sql.safe_mode = On
# Avoid Opening remote files
allow_url_fopen = Off

十五、如果可能让Nginx运行在一个chroot监狱

把nginx放在一个chroot监狱以减小潜在的非法进入其它目录。你可以使用传统的与nginx一起安装的chroot。如果可能,那使用FreeBSD jails,Xen,OpenVZ虚拟化的容器概念。

十六、在防火墙级限制每个IP的连接数

网络服务器必须监视连接和每秒连接限制。PF和Iptales都能够在进入你的nginx服务器之前阻止最终用户的访问。
Linux Iptables:限制每次Nginx连接数

下面的例子会阻止来自一个IP的60秒钟内超过15个连接端口80的连接数。

/sbin/iptables -A INPUT -p tcp –dport 80 -i eth0 -m state –state NEW -m recent –set
/sbin/iptables -A INPUT -p tcp –dport 80 -i eth0 -m state –state NEW -m recent –update –seconds 60 –hitcount 15 -j DROP
service iptables save

请根据你的具体情况来设置限制的连接数。

十七、配置操作系统保护Web服务器

像以上介绍的启动SELinux.正确设置/nginx文档根目录的权限。Nginx以用户nginx运行。但是根目录(/nginx或者/usr /local/nginx/html)不应该设置属于用户nginx或对用户nginx可写。找出错误权限的文件可以使用如下命令:

find /nginx -user nginx
find /usr/local/nginx/html -user nginx

确保你更所有权为root或其它用户,一个典型的权限设置 /usr/local/nginx/html/

ls -l /usr/local/nginx/html/

示例输出:

-rw-r–r– 1 root root 925 Jan 3 00:50 error4xx.html
-rw-r–r– 1 root root 52 Jan 3 10:00 error5xx.html
-rw-r–r– 1 root root 134 Jan 3 00:52 index.html