关于Nginx介绍我就不多说了,下面主要记录一下我所收集的一些有用的配置,多数是和服务器安全相关的。以下部分参考了nixCraft上的《Top 20 Nginx WebServer Best Security Practices》,这篇文章很有借鉴意义,详细讲解了Linux+Nginx服务器安全的方方面面,这篇文章的中译版叫《20个Nginx Web服务器最佳安全实践》。
1. 删除不需要的Nginx模块
我们可能根据我们的需要配置Nginx,当然在编译时可以选择某些不需要的模块不编译进去,比如精简掉autoindex和SSI模块,命令如下:
。/configure --without-http_autoindex_module --without-http_ssi_modulemakemake install
当然在编译前可以通过下面的命令查看那些模块是可以开启或者关闭的:
。/configure --help | less
2. 修改Nginx服务器名称和版本号
著名的NETCRAFT网站可以很轻松的查到你服务器的操作系统和服务程序版本,或者HTTP Response Header也能向我们透露这些信息,很多情况下,这些信息将为黑客进行攻击提供依据,因此我们需要对其进行伪装。
编译Nginx源文件src/http/ngx_http_header_filter_module.c,输入以下命令:
vi +48 src/http/ngx_http_header_filter_module.c
找到下面两行:
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: NOYB” CRLF;static char ngx_http_server_full_string[] = “Server: NOYB” CRLF;
3. 修改Nginx配置文件
3.1 避免缓冲区溢出攻击
修改nginx.conf并且为所有客户端设置缓冲区大小限制:
vi /usr/local/nginx/conf/nginx.conf
编辑并且设置如下:
## Start: Size Limits & Buffer Overflows ## client_body_buffer_size 1K; client_header_buffer_size 1k; client_max_body_size 1k; large_client_header_buffers 2 1k;## END: Size Limits & Buffer Overflows ##
当然也许你还需要配置下面的内容以便于改善服务器性能:
## Start: Timeouts ## client_body_timeout 10; client_header_timeout 10; keepalive_timeout 5 5; send_timeout 10;## End: Timeouts ##
3.2 限制一些访问
仅允许访问我们指定的域名,避免有人扫描绑定当前IP的所有域名,或者避免直接的IP访问以及恶意的域名绑定:
## Only requests to our Host are allowed## i.e. nixcraft.in, images.nixcraft.in and www.nixcraft.in if ($host !~ ^(nixcraft.in|www.nixcraft.in|images.nixcraft.in)$ ) { return 444; }##
当然,网上还流传这么个写法:
server { listen 80 default; server_name _; return 500;}
限制一些方法,一般GET和POST已经够我们用了,其实HTTP还定义有类似于DELETE、SEARCH等方法,用不到的话就拒绝这些方法访问服务器:
## Only allow these request methods ## if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 444; }## Do not accept DELETE, SEARCH and other methods ##
下面这段参考了WordPress的官方Nginx配置。
3.3 全局的限制文件restrictions.conf
# Global restrictions configuration file.# Designed to be included in any server {} block.《/p》location = /favicon.ico { log_not_found off; access_log off;} location = /robots.txt { allow all; log_not_found off; access_log off;} # Deny all attempts to access hidden files# such as .htaccess, .htpasswd, .DS_Store (Mac).location ~ /\。 { deny all; access_log off; log_not_found off;}
建立包含上述内容的文件,然后修改站点配置文件,比如说这里有个示例:
# Redirect everything to the main site.server { server_name *.example.com; root /var/www/example.com; include restrictions.conf; // Additional rules go here.}