使用 mod_rewrite 重定向问题(无扩展名 - 站点根目录)
我在 mod_rewrite 方面遇到了一个小问题 我
的 .htacces 中有以下内容:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.+)\.htm$ index.php?name=$1 [NC]
这是我的 index.php 文件:
<?php echo $_GET['name']; ?>
这对于以下 url 非常有用:
www.mySite.com/这是一个示例.htm
这将显示“这是一个示例”
但是我想做的是让它做同样的事情,没有 .htm 扩展名: 例如:
www.mySite.com/这是一个示例
有什么想法吗?
(不认为它相关,但我正在使用 xampp 来测试它)
I'm having a small problem with mod_rewrite
I have the following in my .htacces:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.+)\.htm$ index.php?name=$1 [NC]
This is my index.php file:
<?php echo $_GET['name']; ?>
This works great for the following url:
www.mySite.com/this is an example.htm
this would display "this is an example"
What i'm trying to do however, is get it to do the same, without the .htm extension:
for example:
www.mySite.com/this is an example
Any ideas?
(dont think it's relevant but i'm using xampp to test this)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在重写规则中将扩展名设置为可选:
请注意,这几乎等同于
除了直接访问 www.mySite.com 之外的任何 URL 都将重定向到 index.php。如果您有更具体的规则,它们应该出现在这一规则之前。
更新: 正如我所说,此规则基本上将匹配 www.mySite.com 上的所有 URL — 包括 index.php!因此,当您访问
www.mySite.com/this is an example
时,会发生以下情况:^(.+)(\.htm)?$
匹配“this是一个示例”^(.+)(\.htm)?$
匹配“index.php”为了防止第二次重定向(指定 [L] 或最后一个不起作用,因为在重新应用第一个重定向规则之后),您可以使用 RewriteCond 指定何时重定向:
这告诉 mod_rewrite 不应用请求 URI(域名后的 URL 部分)是否以 index.php 开头的规则。
您应该查看可以指定的其他重写条件。例如,您可能也不希望用户在直接浏览到另一个 php 文件时被重定向,因此您也可以在
RewriteCond
中指定:其中读取“如果请求不是文件且请求不是index.php,重定向到index.php”。
You can just make the extension optional in your rewrite rule:
Note that this is pretty much the equivalent of
which means that any URL other than going directly to www.mySite.com will redirect to index.php. If you have more specific rules, they should appear before this one.
Update: Like I was saying, this rule will match essentially all URLs on www.mySite.com -- including index.php! Therefore, when you go to
www.mySite.com/this is an example
, the following happens:^(.+)(\.htm)?$
matches "this is an example"^(.+)(\.htm)?$
matches "index.php"In order to prevent the second redirection (specifying [L], or last, doesn't work, because after the first redirection rules are reapplied), you can use a RewriteCond to specify when to redirect:
This tells mod_rewrite to not apply the rule if the request URI (the part of the URL after the domain) starts with index.php.
You should take a look at the other rewrite conditions that you can specify. For example, you probably don't want users to be redirected if they browse directly to another php file, either, so you can specify that in your
RewriteCond
too:Which reads "if the request is not a file and the request is not index.php, redirect to index.php".