简体   繁体   English

.htaccess 使用 RewriteRule 将 url 重定向到 PHP

[英].htaccess redirect a url to PHP using RewriteRule

Trying to setup .htaccess so I can redirect a url like http://example.com/io/abc123 to http://example.com/io/io.php?id=abc123 .尝试设置 .htaccess 以便我可以将像http://example.com/io/abc123这样的网址重定向到http://example.com/io/io.php?id=abc123 But, for some reason, the RewriteRule does not work as I expect.但是,出于某种原因,RewriteRule 并没有像我预期的那样工作。

I want to keep this redirection local without messing up the root .htaccess file, and so I create a new .htaccess file inside the io subdirectory.我想将此重定向保留在本地,而不会弄乱根 .htaccess 文件,因此我在 io 子目录中创建了一个新的 .htaccess 文件。 (Doing the equivalent in the root directory gives the same outcome, so it's not that). (在根目录中执行相同的操作会产生相同的结果,因此并非如此)。

Directory structure:目录结构:

www
 |
 +--io
    |
    +-- .htaccess
    \-- io.php

.htaccess file: .htaccess 文件:

RewriteEngine on
RewriteRule ^(.*)$ io.php?id=$1

io.php file: io.php 文件:

<?php
  echo "Hello World" . "\n";
  echo "REQUEST_URI=[" . $_SERVER['REQUEST_URI'] . "]\n";
  echo "PHP_SELF=[" . $_SERVER['PHP_SELF'] . "]\n";
  echo "QUERY_STRING=[" . $_SERVER['QUERY_STRING'] . "]\n";
  $id = $_GET['id'];
  echo "id='" . $id . "'\n";
  ?>

OUTPUT输出

Hello World
REQUEST_URI=[/io/abc123]
PHP_SELF=[/io/io.php]
QUERY_STRING=[id=io.php]
id='io.php'

For reasons I don't understand, instead of the expected query_string id=abc123 this results in id=io.php .由于我不明白的原因,而不是预期的id=io.php id=abc123这导致id=io.php

It's obviously getting the rewrite correct to the target file io.php , but fails to substitute the abc123 into the id parameter using $1.很明显,目标文件io.php的重写正确,但未能使用 $1 将abc123替换为 id 参数。

What am I doing wrong?我究竟做错了什么?

For reasons I don't understand, instead of the expected query_string id=abc123 this results in id=io.php由于我不明白的原因,而不是预期的 query_string id=abc123 这导致 id=io.php

Reason is that your rule is executing twice since there is no pre-condition to not to rewrite for existing files and directories.原因是您的规则执行了两次,因为没有不重写现有文件和目录的先决条件。

  1. First time it matches abc123 and rewrites to io.php?id=abc123第一次匹配abc123并重写为io.php?id=abc123
  2. Now our REQUEST_URI has become io.php .现在我们的REQUEST_URI变成了io.php mod_rewrite runs in a loop unless there is no executing rule or else if source and target URIs are same. mod_rewrite循环运行,除非没有执行规则或者源和目标 URI 相同。 So second time it matches io.php (since our pattern is .* ) and it gets rewritten to io.php?id=io.php .所以第二次它匹配io.php (因为我们的模式是.* )并且它被重写为io.php?id=io.php

mod_rewrite engine stops here because source and target URIs are same. mod_rewrite引擎在这里停止,因为源和目标 URI 是相同的。

To fix this issue, you should use:要解决此问题,您应该使用:

RewriteEngine On

# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ io.php?id=$1 [L,QSA]

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

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