Linux/VPS環(huán)境下Nginx安全配置小記
關(guān)于Nginx介紹我就不多說了,下面主要記錄一下我所收集的一些有用的配置,多數(shù)是和服務(wù)器安全相關(guān)的。以下部分參考了nixCraft上的《Top 20 Nginx WebServer Best Security Practices》,這篇文章很有借鑒意義,詳細(xì)講解了Linux+Nginx服務(wù)器安全的方方面面,這篇文章的中譯版叫《20個Nginx Web服務(wù)器最佳安全實踐》。
1. 刪除不需要的Nginx模塊
我們可能根據(jù)我們的需要配置Nginx,當(dāng)然在編譯時可以選擇某些不需要的模塊不編譯進(jìn)去,比如精簡掉autoindex和SSI模塊,命令如下:
./configure --without-http_autoindex_module --without-http_ssi_module
make
make install
當(dāng)然在編譯前可以通過下面的命令查看那些模塊是可以開啟或者關(guān)閉的:
./configure --help | less
2. 修改Nginx服務(wù)器名稱和版本號
著名的NETCRAFT網(wǎng)站可以很輕松的查到你服務(wù)器的操作系統(tǒng)和服務(wù)程序版本,或者HTTP Response Header也能向我們透露這些信息,很多情況下,這些信息將為黑客進(jìn)行攻擊提供依據(jù),因此我們需要對其進(jìn)行偽裝。
編譯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;
改成如下,當(dāng)然具體顯示什么你可以自己定義:
static char ngx_http_server_string[] = "Server: NOYB" CRLF;
static char ngx_http_server_full_string[] = "Server: NOYB" CRLF;
3. 修改Nginx配置文件
3.1 避免緩沖區(qū)溢出攻擊
修改nginx.conf并且為所有客戶端設(shè)置緩沖區(qū)大小限制:
vi /usr/local/nginx/conf/nginx.conf
編輯并且設(shè)置如下:
## 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 ##
當(dāng)然也許你還需要配置下面的內(nèi)容以便于改善服務(wù)器性能:
## Start: Timeouts ##
client_body_timeout 10;
client_header_timeout 10;
keepalive_timeout 5 5;
send_timeout 10;
## End: Timeouts ##
3.2 限制一些訪問
僅允許訪問我們指定的域名,避免有人掃描綁定當(dāng)前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;
}
##
當(dāng)然,網(wǎng)上還流傳這么個寫法:
server {
listen 80 default;
server_name _;
return 500;
}
限制一些方法,一般GET和POST已經(jīng)夠我們用了,其實HTTP還定義有類似于DELETE、SEARCH等方法,用不到的話就拒絕這些方法訪問服務(wù)器:
## 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;
}
建立包含上述內(nèi)容的文件,然后修改站點配置文件,比如說這里有個示例:
# Redirect everything to the main site.
server {
server_name *.example.com;
root /var/www/example.com;
include restrictions.conf;
// Additional rules go here.
}