在htaccess中使用重写的友好URL

时间:2012-07-03 03:06:58

标签: php .htaccess mod-rewrite

我有这个网址

http://mysite.com/profile?id=78

我想把它改成像这样

http://mysite.com/78/

我该怎么做?

我的htaccess中有这个代码,但似乎它无效。

RewriteRule ^id/([a-zA-Z0-9]+)/$ profile?id=$1

请指导我这个。

您的帮助将受到高度赞赏和奖励。

谢谢!

4 个答案:

答案 0 :(得分:3)

我很确定你应该使用RewriteBase指令

RewriteEngine On
RewriteBase /
# Use the following rule if you want to make the page like a directory
RewriteRule ^u/(!(profile.php))$ u/$1/ [R=301,L]
# The following rule does the rewrite.
RewriteRule ^u/(!(profile.php))/$ profile.php?name=$1 [L]

这会将http://mysite.com/u/john/重写为http://mysite.com/profile?name=john

修改这是新答案

RewriteEngine On
RewriteBase /
# Use the following rule if you want to make the page like a directory
RewriteRule ^u/(!(profile.php))$ u/$1/ [R=301,L]
# The following rule does the rewrite.
RewriteRule ^u/(!(profile.php))/$ profile.php?name=$1 [L]
# The following rewrite the other way round:
RewriteCond %{REQUEST_URI} ^/profile.php
RewriteCond %{THE_REQUEST} ^(GET|POST|HEAD|TRACE)\ /profile.php
RewriteCond %{QUERY_STRING} name=([^&]+)
RewriteRule ^profile.php$ u/%1? [R=301,L]

答案 1 :(得分:1)

你看到的是正确的。但是,请求可能会再次处理。

您可以通过添加[L]标记并确保映射到确切文件来避免这种情况。例如:

RewriteEngine On

RewriteRule ^name/([a-zA-Z0-9]+)/?$ profile.php?name=$1 [L]

注意:我还将尾随斜杠设为可选。我明确转过RewriteEngine On

答案 2 :(得分:0)

您需要在.htaccess文件中使用此功能:

RewriteEngine On
RewriteRule ^([^/]*)/$ /profile?name=$1 [L]

我用它来生成它:http://www.generateit.net/mod-rewrite/

答案 3 :(得分:0)

我用这种方式解决了它:

RewriteEngine On
RewriteBase /
# Use the following rule if you want to make the page like a directory
RewriteRule ^(v)$ /$1/
# The following rule does the rewrite.
RewriteRule ^(.+)/$ profile.php?id=$1
# The following rewrite the other way round:
RewriteCond %{REQUEST_URI} ^/profile.php
RewriteCond %{THE_REQUEST} ^(GET|POST|HEAD|TRACE)\ /profile.php
RewriteCond %{QUERY_STRING} id=([^&]+)
RewriteRule ^profile.php$ %1?