【问题标题】:Remove File name from URL & keep 2 GET variables in the URL?从 URL 中删除文件名并在 URL 中保留 2 个 GET 变量?
【发布时间】:2020-08-25 16:49:44
【问题描述】:

我正在开发一个网站,我需要在其中创建一个特定的 URL 结构......那么如何制作这个 url:

http://example.com/index.php?city=mumbai&place=chembur

进入这个:

http://example.com/mumbai/chembur

有可能吗?

编辑:

我尝试在 htaccess 文件中使用以下代码,但它显示一个空页面

# RewriteCond %{REQUEST_FILENAME} !-f
# RewriteRule !/$ %{REQUEST_URI}/ [L,R=301]

# RewriteCond %{REQUEST_FILENAME} -f [OR]
# RewriteCond %{REQUEST_FILENAME} -d
# RewriteRule ^ - [L]

# RewriteRule ^([^/]+)/([^/]+)/?$ index.php?city=$1&place=$2 [L,QSA]

# RewriteRule ^([^/]+)/?$ index.php?city=$1 [L,QSA]

编辑:我选择@AbsoluteBeginner 答案是因为它的代码更少且错误为 0。我知道这不是 url 重定向,但它正在解决我的问题。

另外,感谢@CallofDev 提供的这么多帮助!

【问题讨论】:

  • @Evert 我已经编辑了我的问题
  • @anubhava 是的,我测试了 .htaccess 已启用

标签: php .htaccess mod-rewrite


【解决方案1】:

在这里,我们必须分别处理规则,以便在您只有一个变量或两个变量的情况下获得特定的 url。在您的情况下,您所做的事情是为同一规则分配了条件,因此不起作用。所以我们为这两种 URL 格式定义了条件。如果仅传递了 city 的值,则第一个规则将起作用,而仅当两个值都被传递时,另一个规则将起作用。在这里,此链接将帮助您了解如何检查规则https://htaccess.madewithlove.be?share=1fe76858-2b15-5848-bbbe-32e55b692e1e

RewriteEngine on

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

   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteRule ^([^/]+)/([^/]+)$ index.php?city=$1&place=$2 [L]

【讨论】:

  • 您好,感谢您的快速回复。我试过这个,但它给了我找不到对象的错误..(我正在研究 xampp)
  • 您是否尝试在 httpd.conf 文件中将 AllowOverride 更改为 All。
  • 我试过了,但没有用.. 另外,尝试在共享主机上测试它,但它给出了内部服务器错误
  • 谢谢你拯救了我的一天 =D 我在子文件夹中上传了脚本,但后来移到了根目录,它工作了!
  • 很高兴能为您提供帮助。干杯!
【解决方案2】:

您可以使用简单的 PHP 路由器。

.htaccess

FallbackResource index.php

index.php

$path = explode('/', $_SERVER['REQUEST_URI']);
$city = $path[1]; // mumbai
$place = $path[2]; // chembur

// Do what you want with those two variables (database query or include a file).

这将使您完全控制 url 结构。这不是 url 重写,这是一种不同的方法。

【讨论】:

  • 抱歉,我不明白这会如何将此 URL example.com/index.php?city=mumbai&place=chembur 转换为:example.com/mumbai/chembur
  • 现在 URL 是这样的 example.com/?mumbai/chembur 但是我想删除 ?也来自网址
  • 不需要添加?在 example.com 之后,因为没有变量通过 URL 传递。这将是:example.com/mumbai/chembur(正是您想要的)。
猜你喜欢
  • 1970-01-01
  • 2013-01-04
  • 2012-12-22
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-02
  • 1970-01-01
相关资源
最近更新 更多