htaccess重写规则相同的域名

问题描述:

I have a url rewrite issue on the .htaccess file. There are 2 rules on the file:

rule 1 // When user open "example.com/test.php" on a browser then user will be redirected to "example.com/test".

htaccess rule: RewriteRule ^test.php(.*)$ http://example.com/test/$1 [r=301,nc]

rule 2 // When user will open "example.com/test" we will retrieve the content from "example.com/test.php".

htaccess rule: RewriteRule ^test/ test.php [NC]

Right now those rules are not working, maybe there is a conflict somewhere. What rewrite rules i should use for the above conditions?

我在.htaccess文件上有一个url重写问题。 该文件有两个规则: p>

规则1 //当用户在浏览器上打开“example.com/test.php”时,用户将被重定向到“example.com/test “。 p>

  htaccess rule:RewriteRule ^ test.php(。*)$ http://example.com/test/$1 [r = 301,nc] 
   pre> 
 
 

规则2 //当用户打开“example.com/test”时,我们将从“example.com/test.php”中检索内容。 p> \ n

  htaccess rule:RewriteRule ^ test / test.php [NC] 
  code>  pre> 
 
 

现在这些规则不起作用,也许有 在某处发生冲突。 在上述情况下我应该使用哪些重写规则? p> div>

The two rules conflict with one an other. One writes test.php to test and the other writes test to test.php, which is likely to leave you in an infinite loop, either within the rewrite engine or between the browser and server depending on how you implement the rewrite.

To solve this I've used a condition to check the requested URI rather than the URI as its currently rewritten.

Try this:

RewriteRule ^test/$ test.php [NC]

RewriteCond %{THE_REQUEST} ^[A-Z]+\ (/[^\ ]*)\.php[?\ ]
RewriteRule ^test\.php(.*)$ http://example.com/test/$1 [R=301,NC]

Couple of things to note that might also be factors:

  1. You hadn't escaped the dot in test.php in your first rewrite
  2. The Apache MultiViews directive can get in the way and do some rewriting before you get your hands on the on the URI in .htaccess. If you have file test.php, but a request is just made to http://example.com/test, then your htaccess will be working with test.php, not just test as you might expect.
  3. Browsers cache redirects which can make it difficult to diagnose problems