使用MOD_REWRITE从URL中删除查询字符串

时间:2016-08-06 11:28:56

标签: php apache .htaccess mod-rewrite server

好吧,在使用mod_rewrite编写干净的URL时,我遇到了很多问题。 说我有像

这样的链接

http://www.example.com/search.php?q=variable 我想将其转换为干净的URL,如

http://www.example.com/variable

我到目前为止使用以下重写规则

RewriteRule ^/?([a-zA-Z_]+)$ search.php?q=$1 [L]

现在,当我将这个干净的网址直接输入我的浏览器时,它工作正常但是当我打开我的网站并通过我的网站的搜索框查询任何内容时它仍然显示

http://www.example.com/search.php?q=variable

我只想知道如何解决这个问题,因为当我输入干净的URL它工作正常但是从搜索框搜索而不是直接在浏览器中写入URL时它仍然显示带有查询字符串的URL。 感谢任何帮助都会得到满足

2 个答案:

答案 0 :(得分:1)

将您的HTML代码更改为禁用表单提交,并使用此HTML代码段始终使用漂亮的网址:

<html>
<head>
<script>
function prettySubmit(form, evt) {
   evt.preventDefault();
   window.location = '/' + form.q.value.replace(/ /g, '+');
   return false;
}

</script>
</head>
<body>
<form method="get" action="search" onsubmit='return prettySubmit(this, event);'>
   <input type="text" name="q" class="txtfield" 
       value="<?php if (isset($_GET['q'])) echo $_GET['q']; ?>" 
        placeholder="Search Keyword" />
   <input type="submit" name="submit" class="btn" value="Search" />
</form>
</body>
</html>

然后在站点根目录中使用此规则.htaccess:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?([a-zA-Z_]+)$ search.php?q=$1 [L,QSA]

答案 1 :(得分:0)

您可以在以下网站查看所有说明: Complete Tutorial about how to clean url with php and .htacess