inrob
inrob

Reputation: 5089

php search form and url rewrite/formatting

So I'm working on a self project of mine and it is related to job searching. I want the urls to appear as: site.com/search/developer where developer is the search keyword obviously. Now the thing is that as normally when I click search (the submit button does it's job) and the url appears as: site.com/search.php?kword=developer and Im sure htaccess rewrite cannot change the way php forms behave and how they format the url.

Now I have an idea to use javascript so that when user types a keyword, i take that and redirect the page via js to site.com/search/[keyword] but I'm UNSURE if this is a good idea (considering disabled javascript cases).

Is there any decent/recommended way to achieve what I'm trying to achieve, I know there is because I have seen some big websites do it only I dont know what's the best way to do it.

Thank you in advance.

Upvotes: 4

Views: 2041

Answers (1)

anubhava
anubhava

Reputation: 785008

You can certainly use Javascript to make it site.com/search/developer. For the extreme rare case when Javascript is disabled you can let them submit regular HTML form with the final URL as site.com/search.php?kword=developer.

Good news is that using mod_rewrite you can handle both the cases to always have pretty URL in the browser.

Enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# internal forward
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^search/(.+?)/?$ /search.php?kword=$1 [L,QSA,NC]

# external rewrite
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+search\.php\?kword=([^\s]+) [NC]
RewriteRule ^ /search/%1? [R=302,L]

Once you verify it is working fine, replace R=302 to R=301. Avoid using R=301 (Permanent Redirect) while testing your mod_rewrite rules.

Upvotes: 4

Related Questions