简体   繁体   English

使用.htaccess进行动态URL重写

[英]Dynamic URL rewrite using .htaccess

I am pretty new to .htaccess rewrites, and I'm trying to create rules to dynamically rewrite the URLs. 我对.htaccess重写非常陌生,而且我正在尝试创建规则来动态重写URL。

For example, say the user enters the following URL: 例如,假设用户输入以下URL:

http://example.com/xxx/?user=2002

It would be rewritten into: 它将被重写为:

http://example.com/xxx/user/2002/

If user passes multiple parameters like this: 如果用户像这样传递多个参数:

http://example.com/xxx/?user=2002&activity=100&result=true

It should become: 它应该变成:

http://example.com/xxx/user/2002/activity/100/result/

Note: All the query strings will be dynamically generated. 注意:所有查询字符串将动态生成。

This is what I have come up with: 这是我想出的:

<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>

Update 更新

I tried to make the above code and query string rewrite code to work together. 我试图使上面的代码和查询字符串重写代码一起工作。 The modified .htaccess looks like below: 修改后的.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>

Really tricky rules these are. 这些是非常棘手的规则。 Put these recursive rules in your root .htaccess: 将这些递归规则放在根.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