htaccess RewriteRule 解決多種格式的URL解析

弈心逐夢發表於2017-12-28

V1版本的RewriteRule 解析式:

RewriteRule ([a-zA-Z]{1,})/([a-zA-Z]{1,})/([0-9]{1,}).html$ 

能解決格式如:

http://localhost/xxx/ooo/111.html

但是,當需要格式如http://localhost/xxx時,會出問題,如:
輸出連結為http://localhost/test時,出現異常形如下:

Not Found
The requested URL /test was not found on this server.

Apache/2.4.27 (Win64) PHP/5.6.31 Server at localhost Port 80

也就是說,無法支援多種URL寫法。經過嘗試,V2版本.htaccess內容如下:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond $1 !^(index.php\.php|images|robots\.txt)
RewriteRule ([a-zA-Z]{1,})$ /index.php?root=$1
RewriteRule ([a-zA-Z]{1,})/([a-zA-Z]{1,})$ /index.php?root=$1&branch=$2
RewriteRule ([a-zA-Z]{1,})/([a-zA-Z]{1,})/([0-9]{1,}).html$ /index.php?root=$1&branch=$2&leaf=$3

這樣,即可支援多種格式的URL。
示例.htaccess支援的格式形如:

http://localhost/xxx/ooo/111.html
http://localhost/xxx/ooo
http://localhost/xxx

至此,達到目的

相關文章