本文介紹下,在nginx上配置.htaccess偽靜態的方法,有需要的朋友參考下吧。
在apache上.htaccess轉向,只要apache編譯的時候指明支持rewrite模塊即可。
但是換到nginx上方法會有不同,有人說把.htaccess轉向規則寫到nginx的配置文件里面,官方提供的方法之一,肯定可行的。
不過,此方法有個問題:不方便,下次要更改一個偽靜態轉向規則的時候還得去nginx的配置文件或者nginx的虛擬網站的配置文件里面去改,相比apache直接在目錄下放置.htaccess文件,nginx的這個辦法顯然很原始。
解決方法:
在nginx的配置文件中include .htacces文件就可以實現相同的功能了。
舉個例子,要把www.jbxue.com的.htaccess遷移到nginx上,幾個步驟:
第一步:修改.htaccess文件,因為apache的rewrite轉向規則跟nginx的轉向規則還是有一些不一樣的,典型的不一樣有nginx的根目錄需要寫在每行轉向的地址前,每行規則必須以分號(;)結束,301或者404等跳轉使用不同的格式。
apache上htaccess轉換到nginx上:
復制代碼代碼示例:
RewriteEngine On
RewriteBase /
RewriteRule ^show-([0-9]+)-([0-9]+)\.html$ index. php?action=show&id=$1&page=$2
RewriteRule ^category-([0-9]+)-([0-9]+)\.html$ index.php?action=index&cid=$1&page=$2
RewriteRule ^archives-([0-9]+)-([0-9]+)\.html$ index.php?action=index&setdate=$1&page=$2
RewriteRule ^(archives|search|reg|login|index|links)\.html$ index.php?action=$1
RewriteRule ^(comments|tagslist|trackbacks|index)-([0-9]+)\.html$ index.php?action=$1&page=$2
rewriteCond %{http_host} ^jbxue.com [NC]
rewriteRule ^(.*)$ http://www.jbxue.com/$1 [R=301,L]
ErrorDocument 404 http://www.jbxue.com/
RewriteBase /
RewriteRule ^show-([0-9]+)-([0-9]+)\.html$ index. php?action=show&id=$1&page=$2
RewriteRule ^category-([0-9]+)-([0-9]+)\.html$ index.php?action=index&cid=$1&page=$2
RewriteRule ^archives-([0-9]+)-([0-9]+)\.html$ index.php?action=index&setdate=$1&page=$2
RewriteRule ^(archives|search|reg|login|index|links)\.html$ index.php?action=$1
RewriteRule ^(comments|tagslist|trackbacks|index)-([0-9]+)\.html$ index.php?action=$1&page=$2
rewriteCond %{http_host} ^jbxue.com [NC]
rewriteRule ^(.*)$ http://www.jbxue.com/$1 [R=301,L]
ErrorDocument 404 http://www.jbxue.com/
轉換成nginx的規則
復制代碼代碼示例:
rewrite ^/show-([0-9]+)-([0-9]+)\.html$ /index.php?action=show&id=$1&page=$2;
rewrite ^/category-([0-9]+)-([0-9]+)\.html$ /index.php?action=index&cid=$1&page=$2;
rewrite ^/archives-([0-9]+)-([0-9]+)\.html$ /index.php?action=index&setdate=$1&page=$2;
rewrite ^/(archives|search|reg|login|index|links)\.html$ /index.php?action=$1;
rewrite ^/(comments|tagslist|trackbacks|index)-([0-9]+)\.html$ /index.php?action=$1&page=$2;
if ($host != 'www.jbxue.com' ) {
rewrite ^/(.*)$ http://www.jbxue.com/$1 permanent;
}
error_page 404 http://www.jbxue.com/;
rewrite ^/category-([0-9]+)-([0-9]+)\.html$ /index.php?action=index&cid=$1&page=$2;
rewrite ^/archives-([0-9]+)-([0-9]+)\.html$ /index.php?action=index&setdate=$1&page=$2;
rewrite ^/(archives|search|reg|login|index|links)\.html$ /index.php?action=$1;
rewrite ^/(comments|tagslist|trackbacks|index)-([0-9]+)\.html$ /index.php?action=$1&page=$2;
if ($host != 'www.jbxue.com' ) {
rewrite ^/(.*)$ http://www.jbxue.com/$1 permanent;
}
error_page 404 http://www.jbxue.com/;
第二步:修改nginx的配置文件,增加include該.htaccess文件
vi /etc/nginx/sites-available/www.jbxue.com
增加一行:
復制代碼代碼示例:
include /var/www/www.jbxuecom/.htaccess
修改為相應的地址。
第三步:測試並重啟
復制代碼代碼示例:
/etc/init.d/nginx -configtest
重啟生效:
復制代碼代碼示例:
/etc/init.d/nginx restart