Apache重写 - 在PHP中获取原始URL

swa*_*er7 16 php url rewrite

我在nginx或Apache中重写了这个地址:

http://domain.com/hello
Run Code Online (Sandbox Code Playgroud)

像一个脚本

http://domain.com/test.php&ref=hell
Run Code Online (Sandbox Code Playgroud)

如何在PHP中访问此重写的URL?因为,如果我$_SERVER['REQUEST_URI']当然使用我得到:

/test.php&ref=hell
Run Code Online (Sandbox Code Playgroud)

但我只想要:

/hello
Run Code Online (Sandbox Code Playgroud)

这可能吗?Thanx寻求帮助.

Upd nginx cnf

proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

server
{
  listen 80;
  server_name domain.test;


  location /
  {
    rewrite ^/(main|best|air)$ /core/feeds.php?act=$1 last;
    proxy_pass http://127.0.0.1:8080;
  }
}
Run Code Online (Sandbox Code Playgroud)

mar*_*rio 12

这真的取决于PHP设置.使用mod_php,您通常仍然拥有原始请求路径REQUEST_URI.对于CGI或FastCGI设置,这是非常普遍的REDIRECT_URL.您必须检查phpinfo()页面才能确定.

如果你真的找不到任何有用的东西,那就是作弊的时候了!您可以像这样调整RewriteRule,以将原始URL保留在选择的环境变量中:

RewriteRule ^(\w+)$   test.php?ref=$1    [E=ORIG_URI:/$1]
Run Code Online (Sandbox Code Playgroud)

然后可以使用它$_SERVER["ORIG_URI"],或者您可以使用$ _GET ['ref']从URI中获取它.但是你必须在所有潜在的RewriteRules上使用这个技巧.


Phi*_*hil 6

您通常可以在中找到请求的URL

  • $_SERVER['REQUEST_URI']
  • $_SERVER['REDIRECT_URL'] (也许只有Apache,不知道nginx)

我知道你提到的$_SERVER['REQUEST_URI']包含你的重写URL,但在我的所有测试中,它都包含原始请求.

你为什么不转储$_SERVER,看看那里有什么.

  • 不是有问题但是,为了将来参考,在搜索的情况下,`$ _SERVER ['HTTP_X_ORIGINAL_URL']`用于IIS7 +使用IIS Rewrite模块 (3认同)

swa*_*er7 5

Nginxconf中,我们需要添加用户标题request_uri:

proxy_set_header request_uri $request_uri;
Run Code Online (Sandbox Code Playgroud)

阅读php:

echo $_SERVER['HTTP_REQUEST_URI'];
Run Code Online (Sandbox Code Playgroud)

UPD

由于某种原因,nginx不喜欢标题名称中的符号'_',不知道它之前是如何工作的,也许在nginx更新后发生了变化.现在我正在使用

proxy_set_header rewriteduri $request_uri;
Run Code Online (Sandbox Code Playgroud)

在PHP中

$_SERVER['HTTP_REWRITEDURI']
Run Code Online (Sandbox Code Playgroud)

  • 应该注意的是,有些apache配置会将'HTTP_'添加到这样的env变种中,所以它可能位于`$ _SERVER ['request_uri']`(注意案例也是如此) (2认同)