如何创建仅包含查询字符串的URL?

时间:2014-03-01 15:30:04

标签: apache .htaccess url-rewriting

我想在apache web服务器中使用URL重写来拥有这些类型的URL:

www.mysite.com/user.php?id=user1
www.mysite.com/user.php?id=user2
www.mysite.com/user.php?id=me
www.mysite.com/user.php?id=you
www.mysite.com/user.php?id=every_thing

改为

www.mysite.com/user1
www.mysite.com/every_thing

www.mysite.com/user1/

我在我的.htaccess中试过这个。

RewriteEngine On
RewriteRule (.*) user.php?id=$1

它不起作用。有什么问题?

我应该说我有其他目录,如:

www.mysite.com/images/
www.mysite.com/videos/

那么我怎么能这样做呢?它不会发生冲突?

2 个答案:

答案 0 :(得分:1)

你需要在你的根目录.htaccess:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{THE_REQUEST} \s(.+?)/+[?\s]
RewriteRule ^(.+?)/$ /$1 [R=301,L]

RewriteCond %{THE_REQUEST} \s/+user\.php\?id=(\S+) [NC]
RewriteRule ^ /%1? [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)/?$ /user.php?id=$1 [L,QSA]

答案 1 :(得分:0)

改编自wordpress的.htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(user\d) /user.php?id=$1 [L]
</IfModule>