简体   繁体   English

/file.php到/ file /试用

[英]/file.php to /file/ try out

I wanted to redirect/rewrite my name.php files to /name/ I found the solution on another topic (http://stackoverflow.com/questions/5527789/htaccess-rewrite-within-directory-hide-php-extension-and-force-trailing-slash) 我想将我的name.php文件重定向/重写到/ name /我找到了另一个主题的解决方案(http://stackoverflow.com/questions/5527789/htaccess-rewrite-within-directory-hide-php-extension-and -force尾随斜线)

Though, I wanted to learn it myself and started from scratch. 虽然,我想自己学习并从头开始。 I first used this one, which makes eg .com/test/ show the content of .com/test.php: 我首先使用这个,例如.com / test / show .com / test.php的内容:

 RewriteEngine On
 RewriteRule ^(.*)/$ $1.php

Then I tried the following, by itself, which redirects .com/test.php to .com/test/: 然后我尝试了以下内容,将.com / test.php重定向到.com / test /:

 RewriteEngine On
 RewriteRule ^(.*)\.php$ http://www.mydomain.info/$1/ [R=301]

So, both work on their own. 所以,两者都是靠自己工作的。 But when I combine them, I get an loop error, even when I add [L] to it, which should mean the rules should only be used once. 但是当我将它们组合起来时,即使我向它添加[L],也会出现循环错误,这应该意味着规则应该只使用一次。 So this doesn't work: 所以这不起作用:

 RewriteEngine On
 RewriteRule ^(.*)/$ $1.php [L]
 RewriteRule ^(.*)\.php$ http://www.mydomain.info/$1/ [L,R=301]

I've probably made some stupid error but it seems logically to me... Hope someone can point out my error. 我可能犯了一些愚蠢的错误,但对我来说似乎有道理......希望有人可以指出我的错误。 Thanks. 谢谢。

Because you have an external redirect with the R=301 , adding L to it doesn't help as much as you need, as the redirect will come back to the server as a brand new request - where it again matches your first rewrite rule. 因为你有一个R=301的外部重定向,所以添加L对你来说没有多大帮助,因为重定向将作为一个全新的请求返回到服务器 - 它再次匹配你的第一个重写规则。

Instead, you need something like this: 相反,你需要这样的东西:

RewriteCond %{THE_REQUEST} ^\w+\ /(.*)\.php\ HTTP/
RewriteRule ^ /%1/ [R=301]

RewriteRule ^(.*)/$ $1.php

Note that THE_REQUEST matches the entire line of the original request, eg GET /index.php HTTP/1.1 . 请注意, THE_REQUEST匹配原始请求的整行,例如GET /index.php HTTP/1.1 Even when %{REQUEST_URI} is rewritten to .php as part of the 2nd rule (where it will match on an internal sub-request), %{THE_REQUEST} is never rewritten, and this will ensure that the URL rewritten to .php doesn't match on the sub-request and result in another redirect sent back to the client. 即使%{REQUEST_URI}被重写为.php作为第二个规则的一部分(它将在内部子请求中匹配), %{THE_REQUEST}永远不会被重写,这将确保重写为.php的URL不会在子请求上匹配并导致另一个重定向发送回客户端。

Remove L-flag from first rule. 从第一条规则中删除L-flag。 That would stop "executing" and the second rule wouldn't be used. 这将停止“执行”,第二条规则将不会被使用。 At the second rule you should keep the L flag, because it is the last one. 在第二个规则你应该保持L标志,因为它是最后一个。

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

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