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条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀