1. .htaccess文件的作用
.htaccess目錄訪問策略配置文件,放在目錄中,作用與當前目錄及其子目錄。
具體支持:
1. rewrite 重定向路由
2. 設置目錄訪問權限,允許/禁止
3. 自定義404錯誤頁
4. 改變文件擴展名
5. 文件夾密碼保護
2. try_files
try_files是嘗試讀取文件。
try_files $uri $uri/ @locationName;
上面這個try_files的意思是:
1. $uri是nginx的變量,表示用戶訪問的url地址,http://www.xxx.com/index.html, 那么$uri就是 /index.html
2. $url/表示訪問的是一個目錄,http://www.xxx.com/hello/test/, 那么$uri/就是 /hello/test/
3. @locationName表示一個location規則,指向一個location,里面可以配置規則,或者include .htaccess的規則
4. 上面的寫法是,先按$uri找文件,找不到,按后面的$uri/找目錄,最后按照location去找,找不到返回404
實際訪問一個路徑,會判斷是文件還是目錄,文件找$uri, 找不到就location,目錄找$uri/,找不到就location,不會機械的依次查找
3. 偽靜態配置
例如:
http://www.xxx.com/index.php?name=will&age=20 靜態化為 http://www.xxx.com/will/20/index.html
http://www.xxx.com/content/list.php?id=3 靜態化為 http://www.xxx.com/content/list/3.html
3.1 nginx配置:
server { listen 80; server_name localhost; access_log logs/localhost.access.log main; #開啟偽靜態日志,方便調試 rewrite_log on; #輸出錯誤日志,錯誤級別設置為notice error_log logs/error-test.log notice; root html/test; index index.php index.html; location / { try_files $uri $uri/ @locStatic; } //注意使用@符號,不然不成功 location @locStatic { include D:/nginx/html/test/.htaccess; } location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }
3.2 .htaccess配置
在htaccess文件中配置rewrite規則
rewrite 語法格式:
rewrite [regex] [replacement] [flag];
url正則表達式 替換真實url 標記(last,break)
具體配置:
rewrite ^/content/list/([0-9]+).html$ /content/list.php?id=$1 last;
參考:http://blog.sina.com.cn/s/blog_bd418dfa0102wser.html