-2

我开发了一个 PHP 站点,它使用 _GET 变量来构建单个产品页面。(实时)站点的 URL 的当前结构如下:

http://campbellssweets.com/shop/popcorn/product.php?subject=Bacon+and+Cheddar+Popcorn

我有两个问题:

1) 在我的 .htaccess 文件中构造 RewriteCond 和/或 RewriteRule 以从上面的示例中删除“product.php”和查询字符串的正确方法是什么?

2) 同样,我如何将“+”替换为破折号,以便最终 URL 显示为:

http://campbellssweets.com/shop/popcorn/Bacon-and-Cheddar-Popcorn

值得一提的是,我正在利用“保存在子文件夹中的 index.php”方法从类别页面中删除“.php”。

我真的很感激帮助!

我在下面添加了当前的工作流程,希望能更好地解释我的问题。抱歉,如果我在这里做错了什么,这是我的第一篇文章

我有一个类别页面,通过循环列出数据库中的所有项目。页面保存为 index.php:

/shop/popcorn/index.php

类别页面中列出的每个项目都链接到单个产品页面 (product.php),该页面与类别页面位于同一目录中。(product.php) 页面是动态的,其内容取决于 $_GET 变量的值: 生成 product.php 页面的主类别页面的链接如下:

<a href="product.php?subject=<?php echo urlencode($list_savory["product_name"]); ?>">

产品页面 URL(这是此问题的重点)显示为:

shop/popcorn/product.php?subject=Bacon+and+Cheddar+Popcorn

我试图找出正确的 .htaccess 代码,该代码将从 URL 中删除查询字符串并将“+”替换为破折号,以便它们显示为:

商店/爆米花/培根和切达干酪爆米花

Ravi 的回答确实按照我请求的方式格式化了 URL,但是页面无法加载并且我收到“404 Not Found”错误 - 即使在我成功修改 product.php 条件以接受 $_SERVER['REQUEST_URI']而不是 $_GET 变量。

我希望这有助于清除一切。再次抱歉让您感到困惑,我是新手。

4

1 回答 1

1

Assuming your .htaccess is in the web root / directory

RewriteEngine on
RewriteBase /

RewriteCond %{QUERY_STRING} !no-redir [NC]
RewriteCond %{QUERY_STRING} (^|&)subject=([^&]+) [NC]
RewriteRule ^(.*)/product.php$ $1/%2? [NC]

RewriteRule ^([^+\s]+)(?:[+\s]+)([^+\s]+)((?:[+\s]+).*)$ $1-$2$3 [DPI,N]
RewriteRule ^([^+\s]+)(?:[+\s]+)([^+\s]+)$ $1-$2 [R=301,DPI,L]

EDIT : (Parsing the URI for keywords)

Chris, the idea is to now capture the subject from path info instead of a GET parameter because it's not being passed as ?subject=sub+info which makes it unavailable as $_GET['subject'] now.

You'd need to get the subject keywords from the URI path as follows:

$uri = $_SERVER['REQUEST_URI'];
$subject = substr($uri, strrpos($, "/"));

EDIT : (two-way redirection)

Add the following after the rules defined above.

RewriteRule ^(.*/popcorn)/([^/.]+)$ $1/product.php?subject=$2&no-redir [NC,L]

Notice, I've added another RewriteCond on %{QUERY_STRING} above. This also means you can revert your product.php to the way it was before since subject is being passed again as usual.

于 2013-08-15T23:21:47.850 回答