douyan1882 2018-10-02 15:35
浏览 49
已采纳

将查询字符串转换为.php

TL;DR

turn search.php?key=value => value.php

I have a simple project:

|-project
|-----.htaccess
|-----index.php
|-----jquery.min.js
|-----search.php

All I'm trying to learn is how to turn query params into page.php, e.g.:

?search=test becomes test.php

I found this SO post: htaccess rewrite for query string

Which suggests 3 methods of doing it, I've tried all yet my search.php doesn't work.

Here is my index.php

<html>
<body>
    <form method="post">
        <input type="text" name="search" placeholder="search something" />
    </form>

    <button type="button" id="my-btn">Submit</button>

    <script src="jquery.min.js"></script>

    <script>
        jQuery(document).ready(function($)
        {
            $('#my-btn').click(function()
            {
                let val = $('input[type="text"]').val();


                $('form').attr('action', 'search.php?term='+ val);
                $('form').submit()
            })
        })
    </script>
</body>
</html>

which goes to search.php

<?php
    $search = $_GET['search'];

    echo '<pre>';
    echo 'Search Term: <strong>'. $search .'</strong>';
    echo '</pre>';

    echo '<hr />';

and my .htaccess file looks like this:

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ /search.php?term=$1 [L]

But this (or the other methods) didn't work. My url still is search.php?term=test - how do I go about achieving my goal?

  • 写回答

2条回答 默认 最新

  • dongzhong3688 2018-10-02 19:01
    关注

    You may use this code in project/.htaccess:

    RewriteEngine On
    
    # external redirect from actual URL to pretty one
    RewriteCond %{THE_REQUEST} \s/+search(?:\.php)?\?term=([^\s&]+) [NC]
    RewriteRule ^ /%1.php? [R=301,L,NE]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.+)\.php$ search.php?term=$1 [L,QSA,NC]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ search.php?term=$1 [L,QSA]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化