1、Nginx的rewrite規則
php
指令:html
set:設置變量python
if:用來判斷一些在rewrite語句中沒法直接匹配的條件,好比檢測文件存在與否,http header,cookie等nginx
用法: if(條件) {…}正則表達式
- 當if表達式中的條件爲true,則執行if塊中的語句安全
- 當表達式只是一個變量時,若是值爲空或者任何以0開頭的字符串都會看成falseruby
- 直接比較內容時,使用 = 和 !=cookie
- 使用正則表達式匹配時,使用dom
~ 大小寫敏感匹配ide
~* 大小寫不敏感匹配
!~ 大小寫敏感不匹配
!~* 大小寫不敏感不匹配
- 使用-f,-d,-e,-x檢測文件和目錄
-f 檢測文件存在
-d 檢測目錄存在
-e 檢測文件,目錄或者符號連接存在
-x 檢測文件可執行
跟~相似,前置!則爲」非」操做
return:用來直接設置HTTP返回狀態,好比403,404等
break:當即中止rewrite檢測
rewrite:
break – 中止rewrite檢測,當含有break flag的rewrite語句被執行時,該語句就是rewrite的最終結果
last – 中止rewrite檢測,可是跟break有本質的不一樣,last的語句不必定是最終結果.
redirect – 返回302臨時重定向,通常用於重定向到完整的URL(包含http:部分)
permanent – 返回301永久重定向,通常用於重定向到完整的URL(包含http:部分)
瞭解了一些基本的定義下面就直接上配置。
2、nginx配置示例
server { listen 80; server_name www.soul.com soul.com pay.soul.com; root /www; #charset koi8-r; #access_log logs/host.access.log main; location / { index index.php index.html index.htm; } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } ########### 二級域名自動轉到子目錄下 ####################### set $sub_domain ""; if ($http_host ~ "(.+).soul.com$") { set $sub_domain $1; } if ($http_host = "www.soul.com") { set $sub_domain ""; } if ($sub_domain != "") { rewrite /(.+) /$sub_domain/$1 break; } ########################################################### # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # #location ~ /\.ht { # deny all; #} }
上述註釋之間的配置就是讓二級域名自動匹配到根目錄下的域名對對應的子目錄。
3、開啓支持PATH_INFO
一、配置文件示例
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; include fastcgi_params; ############################################################### set $path_info ""; set $real_script_name $fastcgi_script_name; if ($fastcgi_script_name ~ "^(.+?\.php)(/.+)$") { set $real_script_name $1; set $path_info $2; } fastcgi_param SCRIPT_FILENAME $document_root$real_script_name; fastcgi_param SCRIPT_NAME $real_script_name; fastcgi_param PATH_INFO $path_info; ############################################################## }
在location中加入上述註釋內容之間的代碼便可。代碼的意思也很容易看懂。主要是設置path_info的變量。注意的是~\.php沒有$,不然就不會匹配到後面的參數了。
配置完成後,咱們來測試看下效果:
在根目錄下新建index.php文件:
[root@www]# cat index.php <?php echo "<pre>"; print_r($_GET); print_r($_SERVER); exit; require_once('config/common.php'); Route::run(); ?>
訪問測試結果:
能夠看到參數傳遞正常。這種格式也不會報錯了。
4、限制nginx不容許IP和非綁定的域名訪問
測試正常的配置下,把www.baidu.com綁定host到測試機的IP上,測試訪問頁面:
測試都是能夠訪問到咱們默認的頁面的。這樣確定是不安全也是不該該的,下面就進行限制只能經過咱們的域名來訪問:
配置代碼:
# 很簡單的一段代碼:在虛擬主機或者默認配置的server段最開始處添加以下一段server配置: server { listen 80 default; server_name _; return 403; }
重讀配置文件測試效果以下:
能夠看到如今的訪問都是被禁止的。到此配置完成。更多的還能夠關閉顯示版本號等。