[英]Dynamic URL rewrite using .htaccess
我對.htaccess重寫非常陌生,而且我正在嘗試創建規則來動態重寫URL。
例如,假設用戶輸入以下URL:
http://example.com/xxx/?user=2002
它將被重寫為:
http://example.com/xxx/user/2002/
如果用戶像這樣傳遞多個參數:
http://example.com/xxx/?user=2002&activity=100&result=true
它應該變成:
http://example.com/xxx/user/2002/activity/100/result/
注意:所有查詢字符串將動態生成。
這是我想出的:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /news/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /news/index.php [L]
</IfModule>
更新
我試圖使上面的代碼和查詢字符串重寫代碼一起工作。 修改后的.htaccess如下所示:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /news/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /news/index.php [L]
# first take out query string from your /xxx/ URLs
RewriteCond %{QUERY_STRING} ^.+$
RewriteRule ^news/?$ %{REQUEST_URI}/%{QUERY_STRING}? [L]
# now convert & to /
RewriteRule ^([^&]+)&(.*)$ $1/$2 [L]
# now convert = to /
RewriteRule ^([^=]+)=([^=]+=.*)$ $1/$2 [L]
RewriteRule ^([^=]+)=([^=]+)$ $1 [L,R]
# internal rule to replace /n1/v1/n2/v2 to QUERY_STRING
RewriteRule "^(news)/([^/]+)/([^/]*)(/.*)?$" /$1$4?$2=$3 [L,QSA]
</IfModule>
這些是非常棘手的規則。 將這些遞歸規則放在根.htaccess中:
RewriteEngine On
RewriteBase /news/
# first take out query string from your URLs
RewriteCond %{THE_REQUEST} \?\S+
RewriteRule ^/?$ %{QUERY_STRING}? [L]
# now convert all & to /
RewriteRule ^([^&]+)&(.*)$ $1/$2 [L]
# now convert all = to /
RewriteRule ^([^=]+)=([^=]+=.*)$ $1/$2 [L]
RewriteRule ^([^=]+)=([^=]+)$ $1/$2 [L,R]
# finally an internal rule to replace /n1/v1/n2/v2 to QUERY_STRING
RewriteRule "^([^/]+)/([^/]*)(?:/(.*))?$" $3?$1=$2 [L,QSA]
## Your existing stuff followed now
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.