使用.htaccess清除查询字符串URL

时间:2014-08-01 16:26:30

标签: php regex apache .htaccess mod-rewrite

我需要帮助该死的htaccess文件,RegEx只是让我困惑我可以处理基本的重定向但是一旦它进入查询字符串我就会失去它。

所以这就是问题

我正在尝试清理我的网址,因此我想采用原始路径:

http://localhost/webcampaign/projects/project.php?id=1917-Bungalow

让它出现

http://localhost/webcampaign/projects/1917-Bungalow

这是一张文件结构照片,可以提供更好的主意

enter image description here

我将所有项目都设置为像这样的

$projects = array();
$projects["1917-Bungalow"] = array(
 "name" => "1917 Bungalow",
 "heroClass" => "hero-bungalow",
 "mainImg" => BASE_URL ."images/bungalow_main.jpg",
 "previewImg" => BASE_URL ."images/bungalow_preview.jpg",
 "year" => "2013",
 "yearClass" => "twenty13",
 "location" => "Autstin, Texas",
 "photographer" => "Rachel Cruz",
 "detailOne" => BASE_URL ."images/bungalow_detail1.jpg",
 "detailTwo" => BASE_URL ."images/bungalow_detail2.jpg",
 "detailThree" => BASE_URL ."images/bungalow_detail3.jpg",
 "detailFour" => BASE_URL ."images/bungalow_detail4.jpg",
 "description" => "lorem ipsum and shit",
 "detailOneSum" => "lorem ipsum",
 "detailTwoSum" => "lorem ipsum",
 "detailThreeSum" => "lorem ipsum",
 "detailFourSum" => "Lorem ipsum",
 "materials" => array("matOne","matTwo","matThree"),
 "materialImg" => array(BASE_URL ."images/bungalow_mat1.jpg",BASE_URL        .             "images/bungalow_mat2.jpg",BASE_URL ."images/bungalow_mat3.jpg"),
"testamonialImg" => BASE_URL ."images/client.jpg",
"testamonial" => "Cabin Is Great!"
);

然后在project.php页面中,我使用

访问各个项目
 $project_id = $_GET["id"];
 $project = $projects[$project_id];

会有什么影响吗?谢谢,我是一个全新的

这是我对Rewrite的最后一次尝试

RewriteCond %{QUERY_STRING} ^id=(.*)$
RewriteRule ^project.php$ /projects/%1/? [R=301]

对此的任何帮助将不胜感激。 干杯

2 个答案:

答案 0 :(得分:1)

^字符与路径的开头匹配,但网址中的路径以webcampaign而非project.php开头。

尝试从^中删除RewriteRule。我还认为您需要从重定向URL中删除/projects/,因为它看起来就像.htaccess所在的目录。

RewriteEngine On
RewriteBase /webcampaign/

RewriteCond %{QUERY_STRING} ^id=(.*)$
RewriteRule project.php$ projects/%1? [R=301]

修改

因此,基于您更新的问题,您似乎希望与请求的内容相反,因为重写模块只会重写传入的URL,而不是脚本输出的URL。

首先在HTML输出中将链接更改为要显示的格式。这就是评论者所说的"调整html页面上的链接"。

echo '<a href="http://localhost/webcampaign/projects/1917-Bungalow">1917 Bungalow</a>';

接下来,使用这些新的.htaccess规则,使用正确的id参数将上述网址重写到project.php页面:

RewriteEngine On
RewriteBase /webcampaign/

RewriteRule projects/([A-Za-z0-9-]+)/?$ projects/project.php?id=$1 [NC,L]

答案 1 :(得分:0)

将此代码放入DOCUMENT_ROOT/.htaccess文件中:

RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} \s/+(webcampaign/projects)/project\.php\?id=([^\s&]+) [NC]
RewriteRule ^ /%1/%2? [R=302,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(webcampaign/projects)/([^/]+)/?$ $1?id=$2 [L,QSA,NC]