【问题标题】:how to get the url entered from address bar when it is entered manually after domain name in PHP在PHP中手动输入域名后如何获取从地址栏输入的url
【发布时间】:2016-04-09 04:51:34
【问题描述】:

假设我的网站名称是 www.example.com,它是用 php 编写的。 当我键入 www.example.com 时,将显示该页面。但是当我输入 www.example.com/content/somepage.html 时,它说 404 page not found 这是正确的,因为它不存在。

现在,如果用户手动键入此 www.example.com/content/somepage.html,我不应该重定向到错误 404 页面,而是需要 content/somepage.html 这个值我可以进一步处理,这是我的要求。

通常 index.php 是第一个被调用的页面,有什么方法可以获取 www.example.com

之后输入的值

content/somepage.html 只是一个例子,但它可以是任何东西。所以我需要获取 www.example.com 之后的内容。

Sample Download Link

我正在使用 wamp,这两个文件存在于 www 根文件夹中

index.php

<?php 

    echo 'The Uri is : '.$_SERVER['REQUEST_URI'];

    echo '<br /><br />';

    if(isset($_SERVER['path']))
        echo 'The parameter is : '.$_SERVER['path'];

?> 

.htaccess 文件

DirectroyIndex index.php
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?path=$1 [QSA,L]

【问题讨论】:

  • 使用 mod_rewrite 似乎有点矫枉过正(从关于重写规则的问题数量来看,它很容易被破解)。我会使用 ErrorDocument 处理程序 - 例如见stackoverflow.com/questions/9631496/…
  • @symcbean 我看到了但不明白你能说我应该做些什么改变

标签: php html .htaccess


【解决方案1】:

你说的可以用.htaccess换成url routing来实现。

样本

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^content/(\d+)*$ ./index.php?id=$1

根据评论更新。

在最后一行你可以使用 ...

RewriteRule (.*) index.php?url=$1 [L,QSA]

在index.php 文件中,您应该能够以$_GET['url']; 获得字符串的其余部分

【讨论】:

  • 你好 Abdul,实际上在 www.example.com/ 之后发生了什么我需要它。内容词只是我给出的例子,但它可以是任何东西
  • 那么如何获取index.php文件中的值
  • abdul,我仍然得到 404 not found page
  • 我将代码示例下载链接放在我的问题中。我正在我的 wamp 服务器上尝试这个
【解决方案2】:

您可以在站点根目录 .htaccess 中使用此规则:

DirectroyIndex index.php
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?path=$1 [QSA,L]

这将使用 URI 路径 content/somepage.html 填充 /index.php 中的 path 查询参数。


否则使用FallbackResource:

FallbackResource index.php

并在您的/index.php 中使用$_SERVER['REQUEST_URI'] 变量来获取原始URI。

【讨论】:

  • 有什么理由不使用 FallbackResource 而不是 mod_rewrite ?
  • 是的,我没用过,但我可以用 FallbackResource /index.php 代替 RewriteRule ^(.+)$ index.php?path=$1 [QSA,L]
  • @anubhava 我将 FallbackResource /index.php 放在 .htaccess 中,但是当我说 localhost 它工作正常但使用 localhost/sample/contentabc 它重定向到 wamp 服务器主页。如果我从服务器运行并托管它,它会显示 您要查找的资源已被删除、名称已更改或暂时不可用。。我需要 contentabc 或至少我可以解析它的整个 url。
  • @anubhava 它在本地工作,但我尝试在它提供的 azure 网站中托管的示例代码 您要查找的资源已被删除、更改名称或暂时不可用
  • 在我的 Apache 上也可以正常工作。我不知道您的天蓝色网站是如何设置的。什么是Apache版本,什么是DocumentRoot,这个.htaccess在哪里等等。
猜你喜欢
  • 2011-05-05
  • 1970-01-01
  • 1970-01-01
  • 2013-07-04
  • 1970-01-01
  • 1970-01-01
  • 2012-08-23
  • 2021-06-18
  • 2010-12-24
相关资源
最近更新 更多