Nginx 總的 配置文件 位置 /usr/local/nginx/conf/nginx.conf
nginx 正則匹配javascript
一.正則表達式匹配,其中:php
二.文件及目錄匹配,其中:css
三.rewrite指令的最後一項參數爲flag標記,flag標記有:html
使用last和break實現URI重寫,瀏覽器地址欄不變。
使用alias指令必須用last標記;
使用proxy_pass指令時,須要使用break標記。
Last標記在本條rewrite規則執行完畢後,會對其所在server{......}標籤從新發起請求
break標記則在本條規則匹配完成後,終止匹配。前端
四.NginxRewrite 規則相關指令
1.break指令
使用環境:server,location,if;
該指令的做用是完成當前的規則集,再也不處理rewrite指令。java
2.if指令
使用環境:server,location
該指令用於檢查一個條件是否符合,若是條件符合,則執行大括號內的語句。If指令不支持嵌套,不支持多個條件&&和||處理。node
3.return指令
語法:return code ;
使用環境:server,location,if;
該指令用於結束規則的執行並返回狀態碼給客戶端。
示例:若是訪問的URL以".sh"或".bash"結尾,則返回403狀態碼
location ~ .*\.(sh|bash)?$
{
return 403;
}linux
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;
}nginx
5.Set指令
語法:setvariable value ; 默認值:none; 使用環境:server,location,if;
該指令用於定義一個變量,並給變量賦值。變量的值能夠爲文本、變量以及文本變量的聯合。
示例:set $varname "hello world";web
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全局變量
內置變量存放在 ngx_http_core_module 模塊中,變量的命名方式和apache 服務器變量是一致的。總而言之,這些變量表明着客戶端請求頭的內容,例如$http_user_agent, $http_cookie, 等等。
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
例如:容許指定的域名訪問本站,其餘的域名一概轉向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 ,5.0 的未測試