nginx配置說明

來源:互聯網
上載者:User

本日誌內容來自互連網和平日使用經驗,整理一下方便日後參考。

Location文法文法:location [=|~|~*|^~] /uri/ { … }

location = / {
# 只匹配 / 查詢。
[ configuration A ]
}

location / {
# 匹配任何查詢,因為所有請求都已 / 開頭。但是Regex規則和長的塊規則將被優先和查詢匹配。
[ configuration B ]
}

location ^~ /images/ {
# 匹配任何已 /images/ 開頭的任何查詢並且停止搜尋。任何Regex將不會被測試。
[ configuration C ]
}

location ~* .(gif|jpg|jpeg)$ {
# 不區分大小寫匹配任何已 gif、jpg 或 jpeg 結尾的請求。然而所有 /images/ 目錄的請求將使用 Configuration C。
[ configuration D ]
}

Regex匹配,其中:

  1. * ~ 為區分大小寫匹配
  2. * ~* 為不區分大小寫匹配
  3. * !~和!~*分別為區分大小寫不匹配及不區分大小寫不匹配

檔案及目錄匹配,其中:

  1. * -f和!-f用來判斷是否存在檔案
  2. * -d和!-d用來判斷是否存在目錄
  3. * -e和!-e用來判斷是否存在檔案或目錄
  4. * -x和!-x用來判斷檔案是否可執行

flag標記有:

  1. * last 相當於Apache裡的[L]標記,表示完成rewrite
  2. * break 終止匹配, 不再匹配後面的規則
  3. * redirect 返回302臨時重新導向 地址欄會顯示跳轉後的地址
  4. * permanent 返回301永久重新導向 地址欄會顯示跳轉後的地址

一些可用的全域變數有,可以用做條件判斷(待補全)

  1. $args
  2. $content_length
  3. $content_type
  4. $document_root
  5. $document_uri
  6. $host
  7. $http_user_agent
  8. $http_cookie
  9. $limit_rate
  10. $request_body_file
  11. $request_method
  12. $remote_addr
  13. $remote_port
  14. $remote_user
  15. $request_filename
  16. $request_uri
  17. $query_string
  18. $scheme
  19. $server_protocol
  20. $server_addr
  21. $server_name
  22. $server_port
  23. $uri

結合QeePHP的例子

  1. if (!-d $request_filename) {
  2. rewrite ^/([a-z-A-Z]+)/([a-z-A-Z]+)/?(.*)$ /index.php?namespace=user&controller=$1&action=$2&$3 last;
  3. rewrite ^/([a-z-A-Z]+)/?$ /index.php?namespace=user&controller=$1 last;
  4. break;

多目錄轉成參數
abc.domian.com/sort/2 => abc.domian.com/index.php?act=sort&name=abc&id=2

  1. if ($host ~* (.*)/.domain/.com) {
  2. set $sub_name $1;   
  3. rewrite ^/sort//(/d+)//?$ /index.php?act=sort&cid=$sub_name&id=$1 last;
  4. }

目錄對換
/123456/xxxx -> /xxxx?id=123456

  1. rewrite ^/(/d+)/(.+)/ /$2?id=$1 last;

例如下面設定nginx在使用者使用ie的使用重新導向到/nginx-ie目錄下:

  1. if ($http_user_agent ~ MSIE) {
  2. rewrite ^(.*)$ /nginx-ie/$1 break;
  3. }

目錄自動加“/”

  1. if (-d $request_filename){
  2. rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
  3. }

禁止htaccess

  1. location ~//.ht {
  2.          deny all;
  3.      }

禁止多個目錄

  1. location ~ ^/(cron|templates)/ {
  2.          deny all;
  3. break;
  4.      }

禁止以/data開頭的檔案
可以禁止/data/下多級目錄下.log.txt等請求;

  1. location ~ ^/data {
  2.          deny all;
  3.      }

禁止單個目錄
不能禁止.log.txt能請求

  1. location /searchword/cron/ {
  2.          deny all;
  3.      }

禁止單個檔案

  1. location ~ /data/sql/data.sql {
  2.          deny all;
  3.      }

根據檔案類型expires

# Add expires header for static content
location ~* /.(js|css|jpg|jpeg|gif|png|swf)$ {
    if (-f $request_filename) {
       root /data/www/wwwroot/bbs;
       expires      1d;
       break;
    }
}

根據判斷某個目錄

# serve static files
location ~ ^/(images|javascript.|js|css|flash|media|static)/  {
root    /data/www/wwwroot/down;
        expires 30d;
  }

給favicon.ico和robots.txt設定到期時間;
這裡為favicon.ico為99天,robots.txt為7天並不記錄404錯誤記錄檔

  1. location ~(favicon.ico) {
  2.                  log_not_found off;
  3. expires 99d;
  4. break;
  5.      }
  6.  
  7.      location ~(robots.txt) {
  8.                  log_not_found off;
  9. expires 7d;
  10. break;
  11.      }

設定某個檔案的到期時間;這裡為600秒,並不記錄訪問日誌

  1. location ^~ /html/scripts/loadhead_1.js {
  2.                  access_log   off;
  3.                  root /opt/lampp/htdocs/web;
  4. expires 600;
  5. break;
  6.        }

檔案反盜鏈並設定到期時間
這裡的return 412 為自訂的http狀態代碼,預設為403,方便找出正確的盜鏈的請求
“rewrite ^/ http://leech.c1gstudio.com/leech.gif;”顯示一張防盜鏈圖片
“access_log off;”不記錄訪問日誌,減輕壓力
“expires 3d”所有檔案3天的瀏覽器緩衝

  1. location ~* ^.+/.(jpg|jpeg|gif|png|swf|rar|zip|css|js)$ {
  2. valid_referers none blocked *.c1gstudio.com *.c1gstudio.net localhost 208.97.167.194;
  3. if ($invalid_referer) {
  4.     rewrite ^/ http://leech.c1gstudio.com/leech.gif;
  5.     return 412;
  6.     break;
  7. }
  8.                  access_log   off;
  9.                  root /opt/lampp/htdocs/web;
  10. expires 3d;
  11. break;
  12.      }

只充許固定ip訪問網站,並加上密碼

  1. root  /opt/htdocs/www;
  2. allow   208.97.167.194;
  3. allow   222.33.1.2;
  4. allow   231.152.49.4;
  5. deny    all;
  6. auth_basic "C1G_ADMIN";
  7. auth_basic_user_file htpasswd;

將多級目錄下的檔案轉成一個檔案,增強seo效果
/job-123-456-789.html 指向/job/123/456/789.html

  1. rewrite ^/job-([0-9]+)-([0-9]+)-([0-9]+)/.html$ /job/$1/$2/jobshow_$3.html last;

將根目錄下某個檔案夾指向2級目錄
如/shanghaijob/ 指向 /area/shanghai/
如果你將last改成permanent,那麼瀏覽器地址欄顯是/location/shanghai/

  1. rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;

上面例子有個問題是訪問/shanghai 時將不會匹配

  1. rewrite ^/([0-9a-z]+)job$ /area/$1/ last;
  2. rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;

這樣/shanghai 也可以訪問了,但頁面中的相對連結無法使用,
如./list_1.html真真實位址是/area/shanghia/list_1.html會變成/list_1.html,導至無法訪問。

那我加上自動跳轉也是不行咯
(-d $request_filename)它有個條件是必需為真實目錄,而我的rewrite不是的,所以沒有效果

  1. if (-d $request_filename){
  2. rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
  3. }

知道原因後就好辦了,讓我手動跳轉吧

  1. rewrite ^/([0-9a-z]+)job$ /$1job/ permanent;
  2. rewrite ^/([0-9a-z]+)job/(.*)$ /area/$1/$2 last;

檔案和目錄不存在的時候重新導向:

  1. if (!-e $request_filename) {
  2. proxy_pass http://127.0.0.1;
  3. }

網域名稱跳轉

  1. server
  2.      {
  3.              listen       80;
  4.              server_name  jump.c1gstudio.com;
  5.              index index.html index.htm index.php;
  6.              root  /opt/lampp/htdocs/www;
  7.              rewrite ^/ http://www.c1gstudio.com/;
  8.              access_log  off;
  9.      }

多網域名稱轉向

  1. server_name  www.c1gstudio.com www.c1gstudio.net;
  2.              index index.html index.htm index.php;
  3.              root  /opt/lampp/htdocs;
  4. if ($host ~ "c1gstudio/.net") {
  5. rewrite ^(.*) http://www.c1gstudio.com$1 permanent;
  6. }

第三層網域名跳轉

  1. if ($http_host ~* "^(.*)/.i/.c1gstudio/.com$") {
  2. rewrite ^(.*) http://top.yingjiesheng.com$1;
  3. break;
  4. }

網域名稱鏡向

  1. server
  2.      {
  3.              listen       80;
  4.              server_name  mirror.c1gstudio.com;
  5.              index index.html index.htm index.php;
  6.              root  /opt/lampp/htdocs/www;
  7.              rewrite ^/(.*) http://www.c1gstudio.com/$1 last;
  8.              access_log  off;
  9.      }

某個子目錄作鏡向

  1. location ^~ /zhaopinhui {
  2.   rewrite ^.+ http://zph.c1gstudio.com/ last;
  3.   break;
  4.      }

discuz ucenter home (uchome) rewrite

  1. rewrite ^/(space|network)-(.+)/.html$ /$1.php?rewrite=$2 last;
  2. rewrite ^/(space|network)/.html$ /$1.php last;
  3. rewrite ^/([0-9]+)$ /space.php?uid=$1 last;

discuz 7 rewrite

  1. rewrite ^(.*)/archiver/((fid|tid)-[/w/-]+/.html)$ $1/archiver/index.php?$2 last;
  2. rewrite ^(.*)/forum-([0-9]+)-([0-9]+)/.html$ $1/forumdisplay.php?fid=$2&page=$3 last;
  3. rewrite ^(.*)/thread-([0-9]+)-([0-9]+)-([0-9]+)/.html$ $1/viewthread.php?tid=$2&extra=page/%3D$4&page=$3 last;
  4. rewrite ^(.*)/profile-(username|uid)-(.+)/.html$ $1/viewpro.php?$2=$3 last;
  5. rewrite ^(.*)/space-(username|uid)-(.+)/.html$ $1/space.php?$2=$3 last;
  6. rewrite ^(.*)/tag-(.+)/.html$ $1/tag.php?name=$2 last;

給discuz某版塊單獨佈建網域名

  1. server_name  bbs.c1gstudio.com news.c1gstudio.com;
  2.  
  3.      location = / {
  4.         if ($http_host ~ news/.c1gstudio.com$) {
  5.   rewrite ^.+ http://news.c1gstudio.com/forum-831-1.html last;
  6.   break;
  7. }
  8.      }

discuz ucenter 頭像 rewrite 最佳化

  1. location ^~ /ucenter {
  2.      location ~ .*/.php?$
  3.      {
  4.   #fastcgi_pass  unix:/tmp/php-cgi.sock;
  5.   fastcgi_pass  127.0.0.1:9000;
  6.   fastcgi_index index.php;
  7.   include fcgi.conf;     
  8.      }
  9.  
  10.      location /ucenter/data/avatar {
  11. log_not_found off;
  12. access_log   off;
  13. location ~ /(.*)_big/.jpg$ {
  14.     error_page 404 /ucenter/images/noavatar_big.gif;
  15. }
  16. location ~ /(.*)_middle/.jpg$ {
  17.     error_page 404 /ucenter/images/noavatar_middle.gif;
  18. }
  19. location ~ /(.*)_small/.jpg$ {
  20.     error_page 404 /ucenter/images/noavatar_small.gif;
  21. }
  22. expires 300;
  23. break;
  24.      }
  25.                        }

jspace rewrite

  1. location ~ .*/.php?$
  2.              {
  3.                   #fastcgi_pass  unix:/tmp/php-cgi.sock;
  4.                   fastcgi_pass  127.0.0.1:9000;
  5.                   fastcgi_index index.php;
  6.                   include fcgi.conf;     
  7.              }
  8.  
  9.              location ~* ^/index.php/
  10.              {
  11.     rewrite ^/index.php/(.*) /index.php?$1 break;
  12.                   fastcgi_pass  127.0.0.1:9000;
  13.                   fastcgi_index index.php;
  14.                   include fcgi.conf;
  15.              }

 

nginx設定上傳目錄無執行許可權

location ~ ^/upload/.*/.(php|php5)$
{
deny all;
}

其中upload換為你要設定的目錄名字

這條規則的含義是匹配請求串連中開頭是/upload/,中間匹配任一字元,結尾匹配.php或者.php5的頁面,最後利用deny all禁止訪問,這樣就防止了上傳目錄的指令碼執行許可權

 

為nginx設定預設虛擬機器主機(空主機頭,預設主控件頭)

 

nginx的預設虛擬機器主機在使用者通過IP訪問,或者通過未設定的網域名稱訪問(比如有人把他自己的網域名稱指向了你的ip)的時候生效

最關鍵的一點事,在server的設定裡面添加這一行:
listen 80 default;
後面的default參數表示這個是預設虛擬機器主機。

這個設定非常有用。
比如別人通過ip或者未知網域名稱訪問你的網站的時候,你希望禁止顯示任何有效內容,可以給他返回500.
目前國內很多機房都要求網站主關閉空主機頭,防止未備案的網域名稱指向過來造成麻煩。就可以這樣設定:
server {
listen 80 default;
return 500;
}

也可以把這些流量收集起來,匯入到自己的網站,只要做以下跳轉設定就可以:
server {
listen 80 default;
rewrite ^(.*) http://www.myip.net permanent;
}

防盜鏈
針對不同的檔案類型
#Preventing hot linking of images and other file types
location ~* ^.+/.(gif|jpg|png|swf|flv|rar|zip)$ {
        valid_referers none blocked server_names *.linuxtone.org linuxtone.org http://localhost baidu.com;
if ($invalid_referer) {
      rewrite   ^/   ;
     # return   403;
      }
}
針對不同的目錄
location /img/ {
    root /data/www/wwwroot/bbs/img/;
    valid_referers none blocked server_names *.linuxtone.org http://localhost baidu.com;
    if ($invalid_referer) {
                   rewrite  ^/  ;
                   #return   403;
    }
}

同實現防盜鏈和expires的方法

#Preventing hot linking of images and other file types
location ~* ^.+/.(gif|jpg|png|swf|flv|rar|zip)$ {
        valid_referers none blocked server_names *.linuxtone.org linuxtone.org http://localhost ;
if ($invalid_referer) {
      rewrite   ^/   ;
                     }
     access_log off;
     root /data/www/wwwroot/bbs;
expires 1d;
     break;
}

Nginx 身份證驗證

#cd /usr/local/nginx/conf
#mkdir htpasswd
/usr/local/apache2/bin/htpasswd -c /usr/local/nginx/conf/htpasswd/tongji linuxtone
#添加使用者名稱為linuxtone
New password:   (此處輸入你的密碼)
Re-type new password:   (再次輸入你的密碼)
Adding password for user
http://count.linuxtone.org/tongji/data/index.html(目錄存在/data/www/wwwroot/tongji/data/目錄下)
將下段配置放到虛擬機器主機目錄,當訪問http://count.linuxtone/tongji/即提示要密驗證:
location ~ ^/(tongji)/  {
                root    /data/www/wwwroot/count;
                        auth_basic              "LT-COUNT-TongJi";
                        auth_basic_user_file  /usr/local/nginx/conf/htpasswd/tongji;
                }

Nginx 禁止訪問某類型的檔案.
如,Nginx下禁止訪問*.txt檔案,配置方法如下.

location ~* /.(txt|doc)$ {
   if (-f $request_filename) {
   root /data/www/wwwroot/linuxtone/test;
   #rewrite …..可以重新導向到某個URL
   break;
   }
}

location ~* /.(txt|doc)${
        root /data/www/wwwroot/linuxtone/test;
        deny all;
}

推薦參考地址:
Mailing list ARChives 官方討論區
http://marc.info/?l=nginx

Nginx 常見應用技術指南[Nginx Tips]
http://bbs.linuxtone.org/thread-1685-1-1.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.