douyan1882 2018-10-02 07: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 11: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条)
编辑
预览

报告相同问题?