【问题标题】:URL rewriting in PHP [duplicate]PHP中的URL重写[重复]
【发布时间】:2017-09-18 11:00:38
【问题描述】:

大家好,我用 PHP 制作了这个应用程序,不同的页面相互链接在一起。该应用程序运行良好,但生成的 URL 非常混乱和复杂。我的应用程序中有三个页面,即

1.index.php (the default file)
2.video.php (the category page)
3.video-detail.php(the page for playing the video)

并且根文件夹的名字是april

现在为应用程序生成的链接是。

http://localhost/april/video?cat_id=2&category=Programming-Language

考虑到我在第一页中从用户那里获取一些输入后正在浏览某个类别的第二页。现在我正在尝试 URL 应该比这更干净。例如:URL 应该是这种格式。

http://localhost/april/Programming-Language.

我知道这项任务是使用 .htacess 完成的,但我无法真正理解它的方法。因此,我们非常感谢有关此主题的任何帮助。

【问题讨论】:

  • 你使用的是哪个框架?
  • 只是基本的 PHP。连同 apache 服务器。
  • 你必须在 .htaccess 中开启 RewriteEngine

标签: php html .htaccess url web


【解决方案1】:

http://localhost/april/video?category=Programming-Language&cat_id=2

这可以转化为: http://localhost/Programming-Language/2

(请注意,我将cat_id 移到了末尾,因为我怀疑它是页码。)

这是通过将以下内容放入您的.htaccess

RewriteEngine On
RewriteRule ^([^/]*)/([^/]*)$ /april/video?category=$1&cat_id=$2 [L]

显然你可以通过$_GET请求($_GET['category'])获取变量

【讨论】:

  • 试过这种方法。没有成功..这是我的 htaccess 文件。
  • @HarjeevSingh 对于初学者来说,在没有其他东西的情况下尝试它,同时确保你正确使用它。
  • 所以我遇到了这段代码 RewriteRule ^products/([0-9]+)/?$ show_a_product.php?product_id=$1 ,但我似乎无法弄清楚是什么在转换什么。我的意思是教程说它会在 URL 中查找特定模式,然后将其转换为完整的混乱链接。但是这个过程不应该反过来吗?
  • 在 .htaccess 文件的帮助下,我能够将 URL 缩减为 http://localhost/april/24_april/24_april/video-library/2/Programming-Language。现在的问题是每次我运行应用程序时,它首先会加载凌乱的 URL,当我相应地对其进行编辑时,页面也会被加载。那么有什么方法可以让应用程序直接加载干净的 URL,而不是乱七八糟的 URL。
【解决方案2】:

.htaccess中做如下修改

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php

如果您想了解更多信息,请查看这些链接

1.http://httpd.apache.org/docs/trunk/mod/mod_dir.html#fallbackresource 2.https://mediatemple.net/community/products/dv/204643270/using-htaccess-rewrite-rules

【讨论】:

    猜你喜欢
    • 2013-06-23
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多