简体   繁体   English

在htaccess中使用重写的友好URL

[英]Friendly URLs using rewrite in htaccess

I have this url 我有这个网址

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

I wanted to changed it to be like this 我想改变它是这样的

http://mysite.com/78/

How would I do that? 我该怎么办?

I have this code in my htaccess, but it seems it's not working. 我在我的htaccess中有这个代码,但它似乎无法正常工作。

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

Kindly guide me on this one. 请指导我这个。

Your help would be greatly appreciated and rewarded. 您的帮助将受到极大的赞赏和奖励。

Thanks! 谢谢!

I am pretty sure that you should use the RewriteBase directive 我很确定你应该使用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]

This will rewrite http://mysite.com/u/john/ to http://mysite.com/profile?name=john . 这将把http://mysite.com/u/john/重写为http://mysite.com/profile?name=john

Edit this is the new answer 编辑这是新的答案

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]

What you have appears correct. 你有什么看似正确。 However, the request will likely get processed again. 但是,该请求可能会再次处理。

You could avoid that by adding the [L] flag and ensuring you map to the exact file. 你可以通过添加[L]标志并确保映射到确切的文件来避免这种情况。 For example: 例如:

RewriteEngine On

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

Note: I've also made the trailing slash optional. 注意:我也使尾随斜杠可选。 And I explicitly turned the RewriteEngine On 我明确地将RewriteEngine On

You need to use this in your .htaccess file: 您需要在.htaccess文件中使用它:

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

I used this to generate it: http://www.generateit.net/mod-rewrite/ 我用这个来生成它: http//www.generateit.net/mod-rewrite/

I solved it using this way: 我用这种方式解决了它:

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?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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