在 htaccess 中使用重写的友好 URL


Friendly URLs using rewrite in htaccess

我有这个网址

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

我想把它改成这样

http://mysite.com/78/

我该怎么做?

我的htaccess中有这段代码,但它似乎不起作用。

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

请指导我。

您的帮助将不胜感激和回报。

谢谢!

我很确定你应该使用 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]

您拥有的内容看起来是正确的。但是,请求可能会再次得到处理。

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

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

注意:我还使尾部斜杠可选。我明确地把RewriteEngine On

您需要

.htaccess文件中使用它:

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

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

我用这种方式解决了它:

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?