1

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?

treyBake
  • 6,440
  • 6
  • 26
  • 57
  • You may want to look at documentation and check what the arguments for the `RewriteRule` directive do. – miken32 Oct 02 '18 at 15:47
  • @miken32 I looked but honestly not sure it stuck, apache stuff doesn't seem to stick for me .. but I'll keep re-reading until some light turns on – treyBake Oct 02 '18 at 15:59
  • You are way over complicating this simply do this `
    ` and get rid of the JS and rewrite stuff. There is nothing wrong with using a `get` form for a search, in fact that's the most common use of it. That is what it is meant for, so the url query can be bookmarked.
    – ArtisticPhoenix Oct 02 '18 at 16:00
  • @ArtisticPhoenix but text.php is dynamic, e.g. I'd want test.php, or thisguy.php or whatever the search value is ... appended with .php – treyBake Oct 02 '18 at 16:01
  • Another approach is to take the param value, add the extension .php and use it for your needs. If you need to use the php value into jquery consider to json it when assign a php value to a js variable – Sigma Oct 02 '18 at 16:01
  • "The directive consists of three arguments, separated by a space: `RewriteRule pattern substitution [flags]`" https://wiki.apache.org/httpd/RewriteRule – miken32 Oct 02 '18 at 16:02
  • @miken32 I get that - I'm just not particularly good at the pattern/substitution side - thats what never sticks for me :) – treyBake Oct 02 '18 at 16:03
  • making the name of the page dynamic is a bad idea, what if I put `foo` in is there a `foo.php`? Just from a maintenance standpoint it's bad. Use a single entry point the provides dynamic content. What if I put `/../../../../htpasswd` in there? Or `/../../wp-config.php` or something else I shouldn't. – ArtisticPhoenix Oct 02 '18 at 16:03
  • @Sigma thats what I'm trying to do (value + .php) however - that file doesn't physically exist ... how do I get it to go to search.php but render as value.php? – treyBake Oct 02 '18 at 16:03
  • @ArtisticPhoenix that's what I'm trying to do .. behind the scenes is search.php but url renders as foo.php – treyBake Oct 02 '18 at 16:04
  • Well "pattern" is what you're searching for, and "substitution" is what you want to replace it with. Seems like you have things backwards... – miken32 Oct 02 '18 at 16:05
  • Then use the URI component of the URL and not the query string `www.mysite.com/search.php/test` then use HTACCESS to remove the `search.php` and `$_SERVER` to access the URI. Common practice for MVC applications. Besides extensions in the URL is ugly.. – ArtisticPhoenix Oct 02 '18 at 16:06
  • @miken32 yeah I get that, I'm just not sure how to write a regex pattern and what substitute should be – treyBake Oct 02 '18 at 16:06
  • @ArtisticPhoenix agreed it is ugly - I'd prefer to do that, but ultimately, the goal is to rewrite magento urls in layered navigation - I've just set up a really basic project to learn htaccess rewrites and all that jazz - which I'm really struggling with haha if it's not PHP, ThisGuyHasNoThumbs – treyBake Oct 02 '18 at 16:09
  • `^([^.]+)\.php$ search.php?page=$1 [L,QSA]` like that. So `test.php` is matched up to the `.` and put in `$1` - Start with not `.` one or more (greedy) then match `.php` not captured, then end of string. – ArtisticPhoenix Oct 02 '18 at 16:09
  • @ArtisticPhoenix still same results as before :/ – treyBake Oct 02 '18 at 16:12
  • 1
    Learn Regex (Regular Expressions) they are a bit archaic and confusing, but once you understand them they are extremely powerful. If you put `mysite.com/test.php` it will map it to `mysite.com/search.php?page=test` For example https://regex101.com/r/Ax5qBN/1 – ArtisticPhoenix Oct 02 '18 at 16:13
  • 1
    @ArtisticPhoenix I believe that is something I definitely need to improve on and develop skill-wise. Tis probably one of the major things holding back my development – treyBake Oct 02 '18 at 16:14
  • PS these `RewriteCond %{REQUEST_FILENAME} !-f` mean continue if the requested resource does not exists as a real file or dir. `!-f` and `!-d`. So if `test.php` actually exists as a file it won't rewrite it. Don't worry it only takes about 2 years to really learn Regex ... lol – ArtisticPhoenix Oct 02 '18 at 16:20
  • I am bit unclear. When you wrote: ?search=test becomes test.php` do you want to show `domain.com/test.php` in browser but load `search.php?term=test` **internally**? – anubhava Oct 02 '18 at 17:25
  • @ArtisticPhoenix haha look forward to those 2 years xD – treyBake Oct 02 '18 at 18:46
  • @anubhava oui oui mon chere ;) – treyBake Oct 02 '18 at 18:46

2 Answers2

1

How about

RewriteEngine On
RewriteBase /

RewriteCond %{QUERY_STRING} term=(.*)
RewriteRule ^.*$ %1.php [L]
Chris Lear
  • 6,592
  • 1
  • 18
  • 26
  • that produces: `403 forbidden` with message: `You don't have permission to access /.php on this server.` but I think right path maybe? – treyBake Oct 02 '18 at 16:06
  • close .. produced a 404 :S – treyBake Oct 02 '18 at 16:07
  • I've tested this, and it's doing what you expect for me. If you get a 404, is it because the php file doesn't exist? – Chris Lear Oct 02 '18 at 16:11
  • it doesn't - basically, search.php is the file, but in url should look like queryValue.php, e.g. search.php?key=value becomes value.php (with search.php behind it) – treyBake Oct 02 '18 at 16:12
  • "thats what I'm trying to do (value + .php) however - that file doesn't physically exist" :) Seems you are trying to show a different file name on the browser bar but the real file that is executed is another... may by include the file to hide and just execute the fake one – Sigma Oct 02 '18 at 16:12
  • Let me try to get this straight... if someone browses to search.php?term=test, you want their browser to give a 301 sending them to test.php, and then you want apache to run search.php anyway, while the browser url says test.php? – Chris Lear Oct 02 '18 at 16:16
  • @ChrisLear oui oui :) (perhaps I've worded my question a bit to specific to one thing, when in reality I need a much bigger thing) – treyBake Oct 02 '18 at 16:16
  • that's kind of mad :). I'll give it a go – Chris Lear Oct 02 '18 at 16:17
  • @ChrisLear haha yeah - sorta like how /index.php works with Magento except without index.php being there haha – treyBake Oct 02 '18 at 16:17
  • I have to stop now. I've only succeeded in making an endless loop, with search.php?term=test->test.php->search.php?term=test->... – Chris Lear Oct 02 '18 at 16:35
1

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]
anubhava
  • 761,203
  • 64
  • 569
  • 643