Nginx配置文件(nginx.conf)配置詳解
Nginx 總的 配置文件 位置 /usr/local/nginx/conf/nginx.conf
nginx 正則匹配
一.正則表達式匹配,其中:
- ~ 為區分大小寫匹配
- ~* 為不區分大小寫匹配
- !~和!~*分別為區分大小寫不匹配及不區分大小寫不匹配
二.文件及目錄匹配,其中:
- -f和!-f用來判斷是否存在文件
- -d和!-d用來判斷是否存在目錄
- -e和!-e用來判斷是否存在文件或目錄
- -x和!-x用來判斷文件是否可執行
三.rewrite指令的最后一項參數為flag標記,flag標記有:
- last 相當於apache里面的[L]標記,表示rewrite。
- break本條規則匹配完成后,終止匹配,不再匹配后面的規則。
- redirect 返回302臨時重定向,瀏覽器地址會顯示跳轉后的URL地址。
- permanent 返回301永久重定向,瀏覽器地址會顯示跳轉后的URL地址。
使用last和break實現URI重寫,瀏覽器地址欄不變。
使用alias指令必須用last標記;
使用proxy_pass指令時,需要使用break標記。
Last標記在本條rewrite規則執行完畢后,會對其所在server{......}標簽重新發起請求
break標記則在本條規則匹配完成后,終止匹配。
四.NginxRewrite 規則相關指令
1.break指令
使用環境:server,location,if;
該指令的作用是完成當前的規則集,不再處理rewrite指令。
2.if指令
使用環境:server,location
該指令用於檢查一個條件是否符合,如果條件符合,則執行大括號內的語句。If指令不支持嵌套,不支持多個條件&&和||處理。
3.return指令
語法:return code ;
使用環境:server,location,if;
該指令用於結束規則的執行並返回狀態碼給客戶端。
示例:如果訪問的URL以".sh"或".bash"結尾,則返回403狀態碼
location ~ .*\.(sh|bash)?$
{
return 403;
}
4.rewrite 指令
語法:rewriteregex replacement flag
使用環境:server,location,if
該指令根據表達式來重定向URI,或者修改字符串。指令根據配置文件中的順序來執行。注意重寫表達式只對相對路徑有效。如果你想配對主機名,你應該使用if語句
示例如下:
if ( $host ~* www\.(.*) ) { set $host_without_www $1; rewrite ^(.*)$ http://$host_without_www$1 permanent; }
5.Set指令
語法:setvariable value ; 默認值:none; 使用環境:server,location,if;
該指令用於定義一個變量,並給變量賦值。變量的值可以為文本、變量以及文本變量的聯合。
示例:set $varname "hello world";
6.Uninitialized_variable_warn指令
語法:uninitialized_variable_warnon|off
使用環境:http,server,location,if
該指令用於開啟和關閉未初始化變量的警告信息,默認值為開啟。
五.Nginx的Rewrite規則編寫實例
1.當訪問的文件和目錄不存在時,重定向到某個php文件
if ( !-e $request_filename ) { rewrite ^/(.*)$ index.php last; }
2.目錄對換 /123456/xxxx ====> /xxxx?id=123456
rewrite ^/(\d+)/(.+)/ /$2?id=$1 last;
3.如果客戶端使用的是IE瀏覽器,則重定向到/ie目錄下
if( $http_user_agent ~ MSIE) { rewrite ^(.*)$ /ie/$1 break; }
4.禁止訪問多個目錄
location ~ ^/(cron|templates)/ { deny all; break; }
5.禁止訪問以/data開頭的文件
location ~ ^/data
{
deny all;
}
6.禁止訪問以.sh,.flv,.mp3為文件后綴名的文件
location ~ .*\.(sh|flv|mp3)$ { return 403; }
7.設置某些類型文件的瀏覽器緩存時間
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)$ { expires 1h; }
8.給favicon.ico和robots.txt設置過期時間;
這里為favicon.ico為99天,robots.txt為7天並不記錄404錯誤日志
location ~(favicon.ico) { log_not_found off; expires 99d; break; } location ~(robots.txt) { log_not_found off; expires 7d; break; }
9.設定某個文件的過期時間;這里為600秒,並不記錄訪問日志
location ^~ /html/scripts/loadhead_1.js { access_log off; root /opt/lampp/htdocs/web; expires 600; break; }
10.文件反盜鏈並設置過期時間
這里的return412 為自定義的http狀態碼,默認為403,方便找出正確的盜鏈的請求
“rewrite ^/ http://img.linuxidc.net/leech.gif;” 顯示一張防盜鏈圖片
“access_log off;” 不記錄訪問日志,減輕壓力
“expires 3d” 所有文件3天的瀏覽器緩存
location ~*^.+\.(jpg|jpeg|gif|png|swf|rar|zip|css|js)$ { valid_referers none blocked *.linuxidc.com*.linuxidc.net localhost 208.97.167.194; if ($invalid_referer) { rewrite ^/ http://img.linuxidc.net/leech.gif; return 412; break; } access_log off; root /opt/lampp/htdocs/web; expires 3d; break; }
11.只允許固定ip訪問網站,並加上密碼
root /opt/htdocs/www; allow 208.97.167.194; allow 222.33.1.2; allow 231.152.49.4; deny all; auth_basic “C1G_ADMIN”; auth_basic_user_file htpasswd;
12將多級目錄下的文件轉成一個文件,增強seo效果
/job-123-456-789.html 指向/job/123/456/789.html rewrite ^/job-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /job/$1/$2/jobshow_$3.html last;
13.文件和目錄不存在的時候重定向:
if (!-e $request_filename) { proxy_pass http://127.0.0.1; }
14.將根目錄下某個文件夾指向2級目錄
如/shanghaijob/ 指向 /area/shanghai/ 如果你將last改成permanent,那么瀏覽器地址欄顯是/location/shanghai/ rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2last; 上面例子有個問題是訪問/shanghai時將不會匹配 rewrite ^/([0-9a-z]+)job$ /area/$1/ last; rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2last; 這樣/shanghai 也可以訪問了,但頁面中的相對鏈接無法使用, 如./list_1.html真實地址是/area/shanghia/list_1.html會變成/list_1.html,導至無法訪問。 那我加上自動跳轉也是不行咯 (-d $request_filename)它有個條件是必需為真實目錄,而我的rewrite不是的,所以沒有效果 if (-d $request_filename) { rewrite ^/(.*)([^/])$ http://$host/$1$2/permanent; } 知道原因后就好辦了,讓我手動跳轉吧 rewrite ^/([0-9a-z]+)job$ /$1job/permanent; rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2last;
15.域名跳轉
server { listen 80; server_name jump.linuxidc.com; index index.html index.htm index.php; root /opt/lampp/htdocs/www; rewrite ^/ http://www.linuxidc.com/; access_log off; }
16.多域名轉向
server_name www.linuxidc.com www.linuxidc.net; index index.html index.htm index.php; root /opt/lampp/htdocs; if ($host ~ "linuxidc\.net") { rewrite ^(.*) http://www.linuxidc.com$1permanent; }
六.nginx全局變量
arg_PARAMETER #這個變量包含GET請求中,如果有變量PARAMETER時的值。 args #這個變量等於請求行中(GET請求)的參數,如:foo=123&bar=blahblah; binary_remote_addr #二進制的客戶地址。 body_bytes_sent #響應時送出的body字節數數量。即使連接中斷,這個數據也是精確的。 content_length #請求頭中的Content-length字段。 content_type #請求頭中的Content-Type字段。 cookie_COOKIE #cookie COOKIE變量的值 document_root #當前請求在root指令中指定的值。 document_uri #與uri相同。 host #請求主機頭字段,否則為服務器名稱。 hostname #Set to themachine’s hostname as returned by gethostname http_HEADER is_args #如果有args參數,這個變量等於”?”,否則等於”",空值。 http_user_agent #客戶端agent信息 http_cookie #客戶端cookie信息 limit_rate #這個變量可以限制連接速率。 query_string #與args相同。 request_body_file #客戶端請求主體信息的臨時文件名。 request_method #客戶端請求的動作,通常為GET或POST。 remote_addr #客戶端的IP地址。 remote_port #客戶端的端口。 remote_user #已經經過Auth Basic Module驗證的用戶名。 request_completion #如果請求結束,設置為OK. 當請求未結束或如果該請求不是請求鏈串的最后一個時,為空(Empty)。 request_method #GET或POST request_filename #當前請求的文件路徑,由root或alias指令與URI請求生成。 request_uri #包含請求參數的原始URI,不包含主機名,如:”/foo/bar.php?arg=baz”。不能修改。 scheme #HTTP方法(如http,https)。 server_protocol #請求使用的協議,通常是HTTP/1.0或HTTP/1.1。 server_addr #服務器地址,在完成一次系統調用后可以確定這個值。 server_name #服務器名稱。 server_port #請求到達服務器的端口號。
七.Apache和Nginx規則的對應關系
Apache的RewriteCond對應Nginx的if
Apache的RewriteRule對應Nginx的rewrite
Apache的[R]對應Nginx的redirect
Apache的[P]對應Nginx的last
Apache的[R,L]對應Nginx的redirect
Apache的[P,L]對應Nginx的last
Apache的[PT,L]對應Nginx的last
例如:允許指定的域名訪問本站,其他的域名一律轉向http://www.linuxidc.net
Apache:
RewriteCond %{HTTP_HOST} !^(.*?)\.aaa\.com$[NC]
RewriteCond %{HTTP_HOST} !^localhost$
RewriteCond %{HTTP_HOST}!^192\.168\.0\.(.*?)$
RewriteRule ^/(.*)$ http://www.linuxidc.net[R,L]
Nginx:
if( $host ~* ^(.*)\.aaa\.com$ ) { set $allowHost '1'; } if( $host ~* ^localhost ) { set $allowHost '1'; } if( $host ~* ^192\.168\.1\.(.*?)$ ) { set $allowHost '1'; } if( $allowHost !~ '1' ) { rewrite ^/(.*)$ http://www.linuxidc.netredirect ; }
nginx conf 配置文件
nginx進程數,建議設置為等於CPU總核心數. worker_processes 8; 全局錯誤日志定義類型,[ debug | info | notice | warn | error | crit ] error_log /var/log/nginx/error.log info; 進程文件 pid /var/run/nginx.pid; 一個nginx進程打開的最多文件描述符數目,理論值應該是最多打開文件數(系統的值ulimit -n)與nginx進程數相除,但是nginx分配請求並不均勻,所以建議與ulimit -n的值保持一致。 worker_rlimit_nofile 65535; 工作模式與連接數上限 events { #參考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本內核中的高性能網絡I/O模型,如果跑在FreeBSD上面,就用kqueue模型。 use epoll; #單個進程最大連接數(最大連接數=連接數*進程數) worker_connections 65535; } 設定http服務器 http { include mime.types; #文件擴展名與文件類型映射表 default_type application/octet-stream; #默認文件類型 #charset utf-8; #默認編碼 server_names_hash_bucket_size 128; #服務器名字的hash表大小 client_header_buffer_size 32k; #上傳文件大小限制 large_client_header_buffers 4 64k; #設定請求緩 client_max_body_size 8m; #設定請求緩 sendfile on; #開啟高效文件傳輸模式,sendfile指令指定nginx是否調用sendfile函數來輸出文件,對於普通應用設為 on,如果用來進行下載等應用磁盤IO重負載應用,可設置為off,以平衡磁盤與網絡I/O處理速度,降低系統的負載。注意:如果圖片顯示不正常把這個改成off。 autoindex on; #開啟目錄列表訪問,合適下載服務器,默認關閉。 tcp_nopush on; #防止網絡阻塞 tcp_nodelay on; #防止網絡阻塞 keepalive_timeout 120; #長連接超時時間,單位是秒 #FastCGI相關參數是為了改善網站的性能:減少資源占用,提高訪問速度。下面參數看字面意思都能理解。 fastcgi_connect_timeout 300; fastcgi_send_timeout 300; fastcgi_read_timeout 300; fastcgi_buffer_size 64k; fastcgi_buffers 4 64k; fastcgi_busy_buffers_size 128k; fastcgi_temp_file_write_size 128k; #gzip模塊設置 gzip on; #開啟gzip壓縮輸出 gzip_min_length 1k; #最小壓縮文件大小 gzip_buffers 4 16k; #壓縮緩沖區 gzip_http_version 1.0; #壓縮版本(默認1.1,前端如果是squid2.5請使用1.0) gzip_comp_level 2; #壓縮等級 gzip_types text/plain application/x-javascript text/css application/xml; #壓縮類型,默認就已經包含text/html,所以下面就不用再寫了,寫上去也不會有問題,但是會有一個warn。 gzip_vary on; #limit_zone crawler $binary_remote_addr 10m; #開啟限制IP連接數的時候需要使用 upstream blog.ha97.com { #upstream的負載均衡,weight是權重,可以根據機器配置定義權重。weigth參數表示權值,權值越高被分配到的幾率越大。 server 192.168.80.121:80 weight=3; server 192.168.80.122:80 weight=2; server 192.168.80.123:80 weight=3; } 虛擬主機的配置 server { listen 80; #監聽端口 server_name aa.cn www.aa.cn ; #server_name end #域名可以有多個,用空格隔開 index index.html index.htm index.php; # 設置訪問主頁 set $subdomain ''; # 綁定目錄為二級域名 bbb.aa.com 根目錄 /bbb 文件夾 if ( $host ~* "(?:(\w+\.){0,})(\b(?!www\b)\w+)\.\b(?!(com|org|gov|net|cn)\b)\w+\.[a-zA-Z]+" ) { set $subdomain "/$2"; } root /home/wwwroot/aa.cn/web$subdomain;# 訪問域名跟目錄 include rewrite/dedecms.conf; #rewrite end #載入其他配置文件 location ~ .*.(php|php5)?$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi.conf; } #圖片緩存時間設置 location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ { expires 10d; } #JS和CSS緩存時間設置 location ~ .*.(js|css)?$ { expires 1h; } } 日志格式設定 log_format access '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" $http_x_forwarded_for'; #定義本虛擬主機的訪問日志 access_log /var/log/nginx/ha97access.log access; #對 "/" 啟用反向代理 location / { proxy_pass http://127.0.0.1:88; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; #后端的Web服務器可以通過X-Forwarded-For獲取用戶真實IP proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #以下是一些反向代理的配置,可選。 proxy_set_header Host $host; client_max_body_size 10m; #允許客戶端請求的最大單文件字節數 client_body_buffer_size 128k; #緩沖區代理緩沖用戶端請求的最大字節數, proxy_connect_timeout 90; #nginx跟后端服務器連接超時時間(代理連接超時) proxy_send_timeout 90; #后端服務器數據回傳時間(代理發送超時) proxy_read_timeout 90; #連接成功后,后端服務器響應時間(代理接收超時) proxy_buffer_size 4k; #設置代理服務器(nginx)保存用戶頭信息的緩沖區大小 proxy_buffers 4 32k; #proxy_buffers緩沖區,網頁平均在32k以下的設置 proxy_busy_buffers_size 64k; #高負荷下緩沖大小(proxy_buffers*2) proxy_temp_file_write_size 64k; #設定緩存文件夾大小,大於這個值,將從upstream服務器傳 } 設定查看Nginx狀態的地址 location /NginxStatus { stub_status on; access_log on; auth_basic "NginxStatus"; auth_basic_user_file conf/htpasswd; #htpasswd文件的內容可以用apache提供的htpasswd工具來產生。 } #本地動靜分離反向代理配置 #所有jsp的頁面均交由tomcat或resin處理 location ~ .(jsp|jspx|do)?$ { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:8080; } #所有靜態文件由nginx直接讀取不經過tomcat或resin location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$ { expires 15d; } location ~ .*.(js|css)?$ { expires 1h; } }
nginx 在thinkphp 的url 重寫
在/usr/local/nginx/conf/vhost/你的域名配置文件 中添加
location / { if (!-e $request_filename) { rewrite ^/(.*)/(.*)/(.*)/*$ /index.php?m=$1&c=$2&a=$3 last; # thinkphp 的配置文件中 'URL_MODEL' => 1 PATHINFO模式 #或者 rewrite ^(.*)$ /index.php?s=$1 last; # thinkphp 的配置文件中 'URL_MODEL' =>3 兼容模式 #或者 rewrite /(.*)$ /index.php/$1 last; # thinkphp 的配置文件中 'URL_MODEL' => 2 REWRITE模式 break; } }
路徑 pathinfo 模式[ thinkphp ] 添加
location ~ \.php(.*)$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_split_path_info ^((?U).+\.php)(/?.+)$; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; include fastcgi_params; }
重寫 url +省略index.php
location / { try_files $uri /index.php?$uri; }
nginx -s reload 或者 /usr/local/nginx/sbin/nginx -s reload 重新加載Nginx配置文件
(文章中的tp是 thinkphp 3.2.3 )
