引言
nginx軟件十分小巧,較其競爭對手Apache而言,nginx可以實現的功能更爲豐富,配置更爲簡單。Nginx採用多線程方式,對服務器內存大小要求不像apache那些高,此外其處理靜態網頁的速率、併發的訪問量方面等都要比apache出色的多。目前越來越多的國內公司都開始使用nginx來代替apache搭建網站架構。本文介紹了部分常用nginx配置(核心代碼)。
默認虛擬主機
nginx可以實現配置文件的模塊化分離,每個配置文件都是一個獨立的虛擬主機。
[root@localhost default]# vim /usr/local/nginx/conf/vhost/test.com.conf
server
{
# 將該虛擬主機設置爲默認虛擬主機
listen 80 default_server;
# 設置服務器的名稱
server_name default.com;
# 設置服務器默認網頁
index index.html index.htm index.php;
# 設置服務器的根目錄
root /data/www/default;
}
用戶認證
- 核心代碼
# 對目錄
location /admin
{
auth_basic "User Auth";
auth_basic_user_file /usr/local/nginx/conf/htpasswd;
}
# 對文件,可以直接寫文件名,也可以是正則表示
# ~ 匹配,~*模糊匹配(忽略大小寫)
location ~ .*\.php$
{
auth_basic "User Auth";
auth_basic_user_file /usr/local/nginx/conf/htpasswd;
}
域名重定向
實現老站點向新站點域名的重定向
server
{
listen 80;
# nginx可以配置多個主機名,apache只能使用ServerAlias來指定別名
# nginx中哪個主機名在前,就是默認使用的主機名
server_name test.com test2.com;
index index.html index.htm index.php;
root /data/www/test.com;
# 判斷host是否爲test.com
# permanent及返回狀態碼301,永久重定向
if ($host != 'test.com') {
rewrite ^/(.*)$ http://test.com/$1 permanent;
}
}
訪問日誌
# 在nginx主配置文件nginx.conf內添加一下代碼即可
log_format test '$remote_addr $http_x_forwarded_for [$time_local]'
' $host "$request_uri" $status'
' "$http_referer" "$http_user_agent"';
# 設置好日誌格式後,在虛擬主機內的server塊內使用
access_log /tmp/test.com.log test;
# 如果某些情況下不需要記錄日誌,代碼如下
access_log off;
靜態文件不記錄訪問日誌
對於nginx靜態文件訪問日誌不記錄設置而言十分簡單,其核心代碼即expires time;
# 對不同的文件設置不同的過期時間
# 過期時間單位可以是m/h/d等
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 7d;
}
location ~ .*\.(css|js)$
{
expires 12h;
}
防盜鏈
location ~* .*\.(gif|jpg|png|swf|flv|rar|zip|doc|pdf|gz|bz2|jpeg|bmp|xls)$
{
# 白名單可以是多個域名,域名間使用空格間隔開
valid_referers none blocked server_names *.test.com;
# 條件判斷,非白名單域名返回403狀態碼即禁止訪問forbidden;
if ($invalid_referer) {
return 403;
}
}
訪問控制
# 對於目錄
location /admin/
{
# nginx中沒有apache裏的order命令,按代碼先後順序執行
# nginx中只要有一條規則匹配,後續規則就不會進行匹配
# 允許本機
allow 127.0.0.1;
allow 192.168.65.133;
# 禁止其他所有ip
deny all;
}
# 針對文件
location ~ .*(upload|admin)/.*\.php$
{
deny all;
}
# 針對user_agent
location /
{
if ($http_user_agent ~ 'Spider/3.0|YoudaoBot|Tomato')
{
return 403; //等價於deny all;
}
}
php文件解析
location ~ \.php$
{
include fastcgi_params;
# fastcgi_pass參數可以使用ip、sock
# fastcgi_pass 127.0.0.1:9000;
fastcgi_pass unix:/tmp/php-fcgi.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /data/www/test.com$fastcgi_script_name;
}
nginx還可以實現更多更有用的功能,這些知識點不是短短一篇博客就可以將去清楚的,本文基本上時nginx服務器基本功能實現的簡單代碼配置,日常生活工作中還是需要根據具體的需求還進行配置。