开发者

URL Rewriting based on form input

I'm creating a frontpage for my website with a single form and input text, Google-style. It's working fine, however, I want to generate a pretty URL based on the input. Let's say, my input is called "id", and using the GET method of form, and the action defined to "/go/", on submission, the URL will be:

site.com/go/?id=whateverIType

and I want to change it to

site.com/go/whateverIType

I was thinking on Mod Rewrite, but if the user put something in the URL, like:

site.com/go/?dontwant=this&id=whateverIType&somemore=trash

I want to ignore the other开发者_StackOverflow社区 variables but "id", and rewrite the rule.

What's the better way of get this done? Thanks in advance!

PS: I'm using CodeIgniter, maybe there's something I can use for it as well. I already have a controller for "go".


I'm not familiar with CodeIgniter, but you can try the following RewriteRule

RewriteEngine on
RewriteCond %{REQUEST_URI}  ^\/go\/
RewriteCond %{QUERY_STRING} id=([^&]*)
RewriteRule (.*) /go/%1? [L,R]

The %1 references the regex group from the previous RewriteCond, and the trailing ? will strip the querystring from the redirected URL.

Hope this helps.


Mod_rewrite supports conditions and rules with RegEx, so you could have a rule that matched the ?id=XXXX, that would extract it from the URL (keeping the other parameters), and rewrote the URL accordingly.

However... I don't think you want to do this, because if you rewrite the URL to be /go/Some+Search+Query, you won't be able to pick it up with say, PHP, without parsing the URL out manually.

It's really tough to have custom, SEO-friendly URLs with user input, but it is technically possible. You're better off leaving in the ?id=XXX part, and instead, using mod_rewrite in the opposite approach... take all URLs that match the pattern /go/My+Search+Terms and translate that back into something like ?id=My+Search+Terms, that way you'll be able to easily parse out the value using the URL's GET parameters. This isn't an uncommon practice - Google actually still uses URL parameters for user input (example URL: http://www.google.com/search?q=test).

Just keep in mind that mod_rewrite rewrites the URL before anything else (even PHP), so anything you do to the URL you need to handle. Think of mod_rewrite as a regular expression-based, global "Find and Replace" for URLs, every time a page is called on the server. For example, if you remove the query string, you need to make sure your website/application/whatever accounts for that.


In application/config/routes.php

$route['go/(:any)'] = "go/index/$1";

Where go is your controller and index is the index action.

http://codeigniter.com/user_guide/general/routing.html

You can use something like this in your .htaccess if you aren't already:

RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜