treyBake
treyBake

Reputation: 6560

Turn query string into .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?

Upvotes: 1

Views: 94

Answers (2)

anubhava
anubhava

Reputation: 784998

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]

Upvotes: 1

Chris Lear
Chris Lear

Reputation: 6742

How about

RewriteEngine On
RewriteBase /

RewriteCond %{QUERY_STRING} term=(.*)
RewriteRule ^.*$ %1.php [L]

Upvotes: 1

Related Questions