【问题标题】:Changing the page URL and get first two letters更改页面 URL 并获取前两个字母
【发布时间】:2017-12-05 16:37:20
【问题描述】:

如何更改页面 url 查询并获取前两个字母。在 .htaccess 或 php 中

http://127.0.0.1/site/flowers/index.php?query=Bird
http://127.0.0.1/site/flowers/index.php?query=eagle

像这样:

http://127.0.0.1/site/flowers/search/bi/bird.html
http://127.0.0.1/site/flowers/search/ea/eagle.html

Htaccess 代码: 127.0.0.1/site/.htaccess

RewriteEngine on 
RewriteRule ([^/\.]+)/?.html$ index.php?query=$1 [L]

【问题讨论】:

  • 为什么/site/ 中的第一个斜线后有+?你是如何获得/site/flowers/index.php?query=Bird URL 的?是通过某种形式的帖子还是href链接?
  • @anubhava , 先生 .. form post /site/flowers/index.php?query=Bird ....(地址栏)
  • .htacces 位于 > ... 127.0.0.1/site/.htaccess
  • 如果是表单发布,那么我建议在发布之前使用 JS 代码更改 URL。

标签: php .htaccess server


【解决方案1】:

将以下内容添加到您的 .htaccess 中

RewriteRule ([^/\.]+)/?.html$ index.php?query=$1 [R=301]

RewriteCond  %{QUERY_STRING} query=([^/\.]{2})([^/\.]+)
RewriteRule index.php search/%1/%1%2.html [R=301]

然后http://127.0.0.1/site/flowers/Bird.html 重定向到http://127.0.0.1/site/flowers/index.php?query=Bird,而http://127.0.0.1/site/flowers/index.php?query=Bird 又重定向到http://127.0.0.1/site/flowers/search/Bi/Bird.html

我假设这就是你想要的?

【讨论】:

    【解决方案2】:

    这是一个可用于此重定向的 Javascript 代码:

    <html>
    <head>
    <title>Form Post Example</title>
    <script>
    function prettySubmit(form, evt) {
       evt.preventDefault();
       var val = form.query.value.toLowerCase();
       window.location =
              form.action + '/' + val.substr(0, 2) + '/' + val.replace(/ /g, '+') + '.html';
       return false;
    }
    
    </script>
    </head>
    <body>
    <form method="get" action="flowers/search" onsubmit='return prettySubmit(this, event);'>
       <input type="text" name="query">
       <input type="submit" value="Search">
    </form>
    </body>
    </html>
    

    那么你可以在site/.htaccess中拥有这条规则:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ([^/.]+)\.html$ index.php?query=$1 [L,QSA,NC]
    

    这会将您的网址转换为:

    http://127.0.0.1/site/flowers/search/bi/bird.html
    

    当您在搜索字段中使用单词 bird 执行搜索时。

    【讨论】:

    • 非常感谢@anubhava 先生的帮助 :)
    猜你喜欢
    • 2018-04-15
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 2011-09-16
    • 2014-02-12
    • 2011-06-17
    相关资源
    最近更新 更多