繁体   English   中英

使用.htaccess进行动态URL重写

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM